Defining class methods with Modularity traits

Updated . Posted . Visible to the public. Repeats.

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 def

You can def the method on self:

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

However, you cannot use it with traits parameters.

Using define_singleton_method

If you need to use trait parameters (|name| in the example below), you cannot use self.def. Use define_singleton_method instead:

module SomeTrait
  as_trait do |name|
    define_singleton_method :foo do
      puts name
    end
  end
end
Profile picture of Henning Koch
Henning Koch
Last edit
Henning Koch
Keywords
static, method
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-03-08 18:48)