Module: ROM::Model::Attributes::ClassMethods

Defined in:
lib/rom/rails/model/attributes.rb

Overview

Class extensions for an attributes class

Constant Summary collapse

DEFAULT_TIMESTAMPS =

Default timestamp attribute names used by ‘timestamps` method

[:created_at, :updated_at].freeze

Instance Method Summary collapse

Instance Method Details

#[](input) ⇒ Attributes

Process input and return attributes instance

Examples:

class UserAttributes
  include ROM::Model::Attributes

  attribute :name, String
end

UserAttributes[name: 'Jane']

Parameters:

  • input (Hash, #to_hash)

    The input params

Returns:



78
79
80
# File 'lib/rom/rails/model/attributes.rb', line 78

def [](input)
  input.is_a?(self) ? input : new(input)
end

#set_model_name(name) ⇒ undefined

Macro for defining ActiveModel::Name object on the attributes class

This is essential for rails helpers to work properly when generating form input names etc.

Examples:

class UserAttributes
  include ROM::Model::Attributes

  set_model_name 'User'
end

Returns:

  • (undefined)


97
98
99
100
101
102
103
# File 'lib/rom/rails/model/attributes.rb', line 97

def set_model_name(name)
  class_eval <<-RUBY
    def self.model_name
      @model_name ||= ActiveModel::Name.new(self, nil, #{name.inspect})
    end
  RUBY
end

#timestamps(*attrs) ⇒ Object

Shortcut for defining timestamp attributes like created_at etc.

Examples:

class NewPostAttributes
  include ROM::Model::Attributes

  # provide name(s) explicitly
  timestamps :published_at

  # defaults to :created_at, :updated_at without args
  timestamps
end


119
120
121
122
123
124
125
126
127
128
129
# File 'lib/rom/rails/model/attributes.rb', line 119

def timestamps(*attrs)
  if attrs.empty?
    DEFAULT_TIMESTAMPS.each do |t|
      attribute t, DateTime, default: proc { DateTime.now }
    end
  else
    attrs.each do |attr|
      attribute attr, DateTime, default: proc { DateTime.now }
    end
  end
end