Posted about 6 years ago. Visible to the public. Repeats.

Define class methods with Modularity traits

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

Using define_method

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

# ruby 1.9+ module SomeTrait as_trait do define_singleton_method :foo do # ... end end end # ruby <1.9 module SomeTrait as_trait do singleton_class.send :define_method, :foo do # ... end end end

Using def (has caveats!)

Alternatively, you can def the method on self:

module SomeTrait as_trait do def # ... 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 puts name # will raise an error because the variable 'name' is not bound to the method body end end end

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Author of this card:

Henning Koch
Last edit:
about 2 years ago
by Besprechungs-PC
static, method
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandropedia