module Composable::Core::AttributeDSL::ClassMethods
Public Instance Methods
attribute(*attrs)
click to toggle source
# File lib/composable/core/attribute_dsl.rb, line 38 def attribute(*attrs) options = attrs.extract_options! return attributes if attrs.empty? attrs.each do |attribute| _save_options_for(attribute, **options) next if attributes.include?(attribute.to_sym) _define_getter(attribute) _define_setter(attribute) _define_question_mark_method(attribute) attributes << attribute.to_sym end end
Private Instance Methods
_define_getter(attribute)
click to toggle source
# File lib/composable/core/attribute_dsl.rb, line 57 def _define_getter(attribute) define_method(attribute) do options = self.class._attribute_options.fetch(attribute.to_sym, {}) value = if instance_variable_defined?("@#{attribute}") instance_variable_get("@#{attribute}") else instance_variable_set("@#{attribute}", options[:default].deep_dup) end options[:type] ? options[:type].cast(value) : value end end
_define_question_mark_method(attribute)
click to toggle source
# File lib/composable/core/attribute_dsl.rb, line 77 def _define_question_mark_method(attribute) define_method("#{attribute}?") do send(attribute).present? end end
_define_setter(attribute)
click to toggle source
# File lib/composable/core/attribute_dsl.rb, line 70 def _define_setter(attribute) define_method("#{attribute}=") do |value| options = self.class._attribute_options.fetch(attribute.to_sym, {}) instance_variable_set("@#{attribute}", options[:type] ? options[:type].cast(value) : value) end end
_save_options_for(attribute, type: nil, default: nil, **typed_options)
click to toggle source
# File lib/composable/core/attribute_dsl.rb, line 83 def _save_options_for(attribute, type: nil, default: nil, **typed_options) options = _attribute_options[attribute.to_sym] ||= {} options[:default] = default unless default.nil? options[:type] = ActiveModel::Type.lookup(type, **typed_options) unless type.nil? end