user1381745
user1381745

Reputation: 3900

What are before_create, validates_presence_of, has_many etc?

I understand what these statements do, but not how to refer to them. They exist within a class, outside of that class's methods and perform a variety of functions.

Collectively, what are they called?

Upvotes: 1

Views: 104

Answers (2)

janfoeh
janfoeh

Reputation: 10328

These methods are really just class methods. Try this:

class Test
  def self.before_create
    puts "before_create"
  end

  before_create
end

The specific use case you mentioned - Rails DSL methods such as before_create, that are only available inside a class body — are often called class macros. Rubys metaprogramming abilities give you multiple ways to build them. A simple one is to make them private:

module Foo
  private

  def before_create
    puts "before_create"
  end
end

class Bar
  extend Foo

  before_create
end

before_create is now accessible inside the class body, but not from outside:

Bar.before_create
NoMethodError: private method `before_create' called for Bar:Class

Upvotes: 3

Neil Slater
Neil Slater

Reputation: 27207

In pure Ruby terms, they are all just method calls.

However, they do have a common theme. In the way they are constructed and used, you could consider them part of a Domain-Specific Language (DSL) - the ones you list are part of Active Record's DSL for creating data models.

Ruby lends itself well to creating DSL-like mini languages, using mix-ins or a base class in order to provide a set of class methods, which in turn will store data or create methods on the class and instances of it using meta-programming techniques.

Upvotes: 1

Related Questions