« back to all cards in this deck
Posted about 3 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.

1. Using define_method

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

module SomeTrait as_trait do singleton_class.send :define_method, :foo do # ... end end end

2. Use 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, but still discouraged because 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

Author of this card:

Avatar
Henning Koch
Keywords:
static, method
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
Posted by Henning Koch to makandropedia