Posts Tagged ‘Ruby

One for my own records….
It’s:
1cap deploy:migrations
Not!
1cap deploy:migration

Add this to your ~/.bash_profile (~/.profile on OSX) and gain a ‘trs’ shortcut to reboot mod_rails. Bliss ;]
1alias trs=’touch tmp/restart.txt’

When rendering a collection of partials in Rails you can access a sneaky iteration counter from inside each partial using the partial name appended with _counter:
So in the view / partial that calls the collection of partials:
1<%= render :partial => "partial_name", :collection => stuff_to_loop_over %>
Then in your called partial:
12<%= partial_name_counter %>
# Outputs the count 0,1,2,3,4 [...]

To return a class name as a string in Ruby you need this code:
Ruby:
1class_name = thing.class.to_s
I’m also reliably informed you can do this too. Not tested it yet though:
1class_name = thing.class.name
That feels more logical to me.
PHP equivalent:
1$class_name = get_class($thing);

I managed to instantiate Rails Active Record models dynamically with the following code:
123456table_name = ‘table_name_string’
model = Class.new(ActiveRecord::Base) do
   set_table_name table_name
end

model.find(:all)
This would roughly be the equivalent in PHP:
12$object_name = ‘object_name_string’;
$object = new $object_name;

Following on from my last post. I needed to set an object attribute/member dynamically in Ruby:
In PHP that would be:
12$member_variable = ‘member_variable_name’;
$object->$member_variable = ‘value’;
After the usual stack of Googling, the Ruby way:
12member_variable = ‘member_variable_name’
object.send((member_variable + "=").to_sym, ‘value’)

I needed to access a Ruby object member (attribute) today, dynamically, using a string variable to make the call.
In PHP I would have done this:
123$member_name = ‘dynamic_member_name’;

$object->$member_name;
After a bit of Googling I figured out the Ruby way:
123member_name = ‘dynamic_member_name’

object.send(member_name)
Hmmmmmm. Must say that feels a bit weird. I’m sure it’s proper OO though.

This might help someone:
Today I was trying to build a form that was going to be used as an include/partial on multiple pages of a website. So I needed each included version to submit to its parent page (itself). I was going to handle each submission with a before filter in the application controller. I [...]

Useful to find out if one number is divisible by another, in this case 2:
PHP:
123if($c % 2 == 0){
    # It is.
}
Ruby
123if c % 2 == 0
  # It is
end

This works as a rtrim equivalent. I’m trimming a comma (,) in this example.
PHP:
1$variable = rtrim($variable, ‘,’);
Ruby:
Could be a one liner but it’s easy to see how the Regex is working with this example.
12rtrim_chars = ","
variable = variable.gsub(/[#{rtrim_chars}]+$/, ”)


top