Read more

Defining class methods with Modularity traits

Henning Koch
March 08, 2011Software engineer at makandra GmbH

There are two ways to define a class method from a Modularity Show archive.org snapshot trait. Note that the usual caveats regarding class method visibility apply.

Using define_method

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

The recommended way is to define a method on your module's singleton class:

module SomeTrait
  as_trait do
    define_singleton_method :foo do
      # ...
    end
  end
end

Using def (has caveats!)

Alternatively, you can def the method on self:

module SomeTrait
  as_trait do
    def self.foo
      # ...
    end
  end
end

This is quite concise and results in faster methods than using define_method. However, you cannot use it with parametrized traits.

The following will fail:

module SomeTrait
  as_trait do |name|
    def self.foo
      puts name # will raise an error because the variable 'name' is not bound to the method body
    end
  end
end
Posted by Henning Koch to makandra dev (2011-03-08 19:48)