Metaprogramming in ruby Let your program extend itself on rutime | 19. Februar 2010 um 01:14 Uhr / Programming

Eingestellt am 19. Februar 2010 um 01:14 Uhr » Programming

This is kind of cool. I love programming in ruby.

Here is the thing; I have models with methods for localized strings like description_en, description_de and name_en, name_fr and so on. I wanted to have just a simple getter like description or name and with some magick it should know which of the localized methods to call.

So I wrote just some lines of code:

# lib/localized_attributes.rb
module LocalizedAttributes
  def localize(*methods)
    methods.each do |method|
      class_eval %Q[
        def #{method}
          #{method}_#{I18n.locale}
        end
      ]
    end
  end
end

# configuration.rb
DefaultModel.extend LocalizedAttributes

# some_model.rb
class SomeModel < DefaultModel
  localize :name, :description
end

# some_view.html.erb
<p>Name: <%= @some_model.name %></p>
<p>Description: <%= @some_model.description %></p>

I suspect the whole rails thing is build like that, but I don't have proof ;-)


Kommentare

  Dein Kommentar 

Wie benutze ich BBcode?