Module: AmberComponent::Props::ClassMethods
- Included in:
- Base
- Defined in:
- lib/amber_component/props.rb
Overview
Class methods for component properties.
Instance Attribute Summary collapse
Instance Method Summary collapse
- #prop(*names, type: nil, required: false, default: nil, allow_nil: false) ⇒ Object
- #prop_names ⇒ Array<Symbol>?
- #required_prop_names ⇒ Array<Symbol>?
Instance Attribute Details
#prop_definitions ⇒ Hash{Symbol => AmberComponent::Prop} (readonly)
12 13 14 |
# File 'lib/amber_component/props.rb', line 12 def prop_definitions @prop_definitions end |
Instance Method Details
#prop(*names, type: nil, required: false, default: nil, allow_nil: false) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/amber_component/props.rb', line 19 def prop(*names, type: nil, required: false, default: nil, allow_nil: false) @prop_definitions ||= {} include(@prop_methods_module = ::Module.new) if @prop_methods_module.nil? names.each do |name| @prop_definitions[name] = prop_def = PropDefinition.new( name: name, type: type, required: required, default: default, allow_nil: allow_nil ) raise IncorrectPropTypeError, <<~MSG unless type.nil? || type.is_a?(::Class) `type` should be a class but received `#{type.inspect}` (`#{type.class}`) MSG @prop_methods_module.attr_reader name next @prop_methods_module.attr_writer(name) unless prop_def.type? @prop_methods_module.class_eval( # rubocop:disable Style/DocumentDynamicEvalDefinition # def phone=(val) # raise IncorrectPropTypeError, <<~MSG unless val.nil? || val.is_a?(String) # #{self.class} received `#{val.class}` instead of `String` for `phone` prop # MSG # # @phone = val # end <<~RUB, __FILE__, __LINE__ + 1 def #{name}=(val) raise IncorrectPropTypeError, <<~MSG unless #{allow_nil ? 'val.nil? ||' : nil} val.is_a?(#{prop_def.type}) \#{self.class} received `\#{val.class}` instead of `#{prop_def.type}` for `#{name}` prop MSG @#{name} = val end RUB ) # rubocop:disable Layout/HeredocArgumentClosingParenthesis end end |
#prop_names ⇒ Array<Symbol>?
60 61 62 |
# File 'lib/amber_component/props.rb', line 60 def prop_names @prop_definitions.keys end |
#required_prop_names ⇒ Array<Symbol>?
65 66 67 68 69 70 71 |
# File 'lib/amber_component/props.rb', line 65 def required_prop_names @prop_definitions&.filter_map do |name, prop_def| next unless prop_def.required name end end |