Method: ViewModel#initialize

Defined in:
app/models/view_model.rb

#initialize(hash = {}) ⇒ ViewModel

View Model

A View Model is a class that allows you to set an arbitrary hash of attributes and access all values by calling attribute methods.

Examples

model = ViewModel.new(a: 1, b: {b1: 1, b2: 2}, c: 3)

model.a   # => 1
model.b   # => {b1: 1, b2: 2}
model.c   # => 3

Reserved methods or attributes are left untouched. If you want to access an attribute that collides with a reserved method, you can do it via the to_hash method.

model = ViewModel.new(class: "test")

model.class             # => ViewModel
model.to_hash[:class]   # => "test"


25
26
27
28
29
# File 'app/models/view_model.rb', line 25

def initialize(hash = {})
  hash.each do |key, value|
    instance_variable_set("@#{key}", value)
  end
end