Posts Tagged ‘Ruby on Rails

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;

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 [...]

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}]+$/, ”)

It’s probably a better idea to use the following to check types in Ruby.
1array.is_a?(Array)
I got caught out earlier trying this:
1array.class # Returns: Array
The returned ‘Array’ value is NOT a string but the actual class. So the following will not equate to true:
123if array.class == ‘Array’
#Do stuff
end
But this will:
123if array.class.to_s == ‘Array’
#Do stuff
end
Must admit, I prefer [...]

You can’t unset an array in Ruby! You set it to nil and let the garbage collector take care of it!
1array = nil

If you want to use the /lib/ directory in a Ruby on Rails application to store .rb files that contain constants. For some (name spacing / scoping?) reason they must be written in a class declaration:
Contents of /lib/constants.rb
123def ConstantClass
  CONSTANT_NAME = ’some value’
end
Then access these constants using the scope resolution operator in your views/controllers:
1<p><%= ConstantClass::CONSTANT_NAME [...]


top