Class: ViewModel
- Inherits:
-
Object
- Object
- ViewModel
- Defined in:
- app/models/view_model.rb
Direct Known Subclasses
Headmin::BlocksView, Headmin::Filter::BaseView, Headmin::Filter::ButtonView, Headmin::Filter::ConditionalView, Headmin::Filter::FilterView, Headmin::Filter::FlatpickrView, Headmin::Filter::MenuItemView, Headmin::Filter::OperatorView, Headmin::Filter::RowView, Headmin::Filter::SearchView, Headmin::Form::AssociationView, Headmin::Form::BlocksView, Headmin::Form::CheckboxView, Headmin::Form::ColorView, Headmin::Form::DateRangeView, Headmin::Form::DateView, Headmin::Form::DatetimeRangeView, Headmin::Form::DatetimeView, Headmin::Form::EmailView, Headmin::Form::FileView, Headmin::Form::FlatpickrRangeView, Headmin::Form::FlatpickrView, Headmin::Form::HiddenView, Headmin::Form::HintView, Headmin::Form::InputGroupView, Headmin::Form::LabelView, Headmin::Form::MediaItemView, Headmin::Form::MediaView, Headmin::Form::NumberView, Headmin::Form::PasswordView, Headmin::Form::RedactorxView, Headmin::Form::SearchView, Headmin::Form::SelectView, Headmin::Form::SwitchView, Headmin::Form::TextView, Headmin::Form::TextareaView, Headmin::Form::UrlView, Headmin::Form::WrapperView, Headmin::Form::WysiwygView, Headmin::ThumbnailView
Instance Method Summary collapse
- #attributes ⇒ Object
-
#initialize(hash = {}) ⇒ ViewModel
constructor
View Model.
- #to_hash ⇒ Object (also: #to_h)
Constructor Details
#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 |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args, &block) ⇒ Object (private)
51 52 53 |
# File 'app/models/view_model.rb', line 51 def method_missing(m, *args, &block) instance_variable_get("@#{m}") end |
Instance Method Details
#attributes ⇒ Object
31 32 33 |
# File 'app/models/view_model.rb', line 31 def attributes instance_variables.map { |instance_variable| instance_variable.to_s.delete("@").to_sym } end |
#to_hash ⇒ Object Also known as: to_h
35 36 37 |
# File 'app/models/view_model.rb', line 35 def to_hash attributes.map { |attribute| {attribute => value_for(attribute)} }.inject(:merge) || {} end |