Monthly Archives: July 2012

how generate a scaffold on already created model?

If you have already created data models in your rails app but wish to scaffold or stub out the controller and the views without starting over the models, you can use the option scaffold_controller

rails generate scaffold_controller <name_of_controller_or_model_pluralized>

For a list of possible generation options, use the -h flag for help.

rails generate -h

String to Boolean conversion

Ever wonder how to convert  the String values of “true” or “false” to the boolean value true false in rails? Rails, specifically ActiveRecord::ConnectionAdapters::Column has a built in function which does just this called value_to_boolean.  

Example(s):

"true".value_to_boolean

params[:is_string_true_false].value_to_boolean

will return the boolean value true.

 

For plain old Ruby, this is not so straightforward, but simple enough.  Since you can very easily override Ruby core classes, we’re going to override the Ruby String class and add a to_bool function which converts a String value to Boolean.

Now we can call on this method for any string. “True”.to_bool ==> true. If you pay attention to the code, you’ll notice that “1” “yes” “y” will be converted to true, and “f”, “no”, “n”, “0”, will convert to false. This works the same for value_to_boolean in rails. This is particularly helpful when getting data from form inputs.

 

* Caution!: One thing to note for the to_bool implementation. “”.to_bool will return false. (that is quotes with no spaces in between).

a better case(switch) statement in Ruby

When multiple conditions (OR) in case statement lead to the same code.

Tedious and inefficient way….

A much better way and not to mention more efficient way to write the same thing…

Both have the same meaning and reads, “when the telecom_type_code is either 1, 2, 3, or 4, assign the telecom_value to phone_number, and tel_url_scheme to url_sheme.  When the type is 5 it is going to be an email assignment.