Module: Granite::Form::Model::Attributes::ClassMethods

Defined in:
lib/granite/form/model/attributes.rb

Instance Method Summary collapse

Instance Method Details

#add_attribute(reflection_class, *args, &block) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/granite/form/model/attributes.rb', line 35

def add_attribute(reflection_class, *args, &block)
  reflection = reflection_class.build(self, generated_attributes_methods, *args, &block)
  self._attributes = _attributes.merge(reflection.name => reflection)
  should_define_dirty = dirty? && reflection_class != Granite::Form::Model::Attributes::Reflections::Base
  define_dirty(reflection.name, generated_attributes_methods) if should_define_dirty
  reflection
end

#alias_attribute(alias_name, attribute_name) ⇒ Object

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/granite/form/model/attributes.rb', line 43

def alias_attribute(alias_name, attribute_name)
  reflection = reflect_on_attribute(attribute_name)
  raise ArgumentError, "Unable to alias undefined attribute `#{attribute_name}` on #{self}" unless reflection

  if reflection.class == Granite::Form::Model::Attributes::Reflections::Base
    raise ArgumentError,
          "Unable to alias base attribute `#{attribute_name}`"
  end

  reflection.class.generate_methods alias_name, generated_attributes_methods
  self._attribute_aliases = _attribute_aliases.merge(alias_name.to_s => reflection.name)
  define_dirty alias_name, generated_attributes_methods if dirty?
  reflection
end

#attribute_names(include_associations = true) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/granite/form/model/attributes.rb', line 68

def attribute_names(include_associations = true)
  if include_associations
    _attributes.keys
  else
    _attributes.map do |name, attribute|
      name unless attribute.class == Granite::Form::Model::Attributes::Reflections::Base
    end.compact
  end
end

#dirty?Boolean

Returns:



82
83
84
# File 'lib/granite/form/model/attributes.rb', line 82

def dirty?
  false
end

#has_attribute?(name) ⇒ Boolean

rubocop:disable Naming/PredicateName

Returns:



63
64
65
66
# File 'lib/granite/form/model/attributes.rb', line 63

def has_attribute?(name) # rubocop:disable Naming/PredicateName
  name = name.to_s
  _attributes.key?(_attribute_aliases[name] || name)
end

#inspectObject



78
79
80
# File 'lib/granite/form/model/attributes.rb', line 78

def inspect
  "#{original_inspect}(#{attributes_for_inspect.presence || 'no attributes'})"
end

#reflect_on_attribute(name) ⇒ Object



58
59
60
61
# File 'lib/granite/form/model/attributes.rb', line 58

def reflect_on_attribute(name)
  name = name.to_s
  _attributes[_attribute_aliases[name] || name]
end

#with_sanitize(value) ⇒ Object



86
87
88
89
90
91
92
# File 'lib/granite/form/model/attributes.rb', line 86

def with_sanitize(value)
  previous_sanitize = _sanitize
  self._sanitize = value
  yield
ensure
  self._sanitize = previous_sanitize
end