Module: HasHelpers::Attributes::GuardedAttributes
- Included in:
- UIAttributes, UIAttributes::HTMLAttributes
- Defined in:
- lib/has_helpers/attributes.rb
Overview
GuardedAttributes provides--and combines!--shortcuts for many common patterns of accessor methods.
Take for example this service accessor. There is a normal writer method which lets the user
optionally set service. The reader method should always return either nil or a Service
object, which is ensured by calling to_service, the "guard" method.
attr_writer :service
def service
@service && @service.to_service
end
guarded_attr_accessor does all that in one line. guarded_attr_accessor is smart and will convert
the object passed in as the guard to a Proc, so you may simply pass in a symbol. There is also an
auto_guard option which will generate the Proc based on the attribute name. The following lines
are all equivalent:
guarded_attr_accessor :service, guard: -> value { value.to_service }
guarded_attr_accessor :service, guard: :to_service
guarded_attr_accessor :service, auto_guard: true
auto_guard is most convenient when defining multiple attributes.
guarded_attr_accessor :service, :icon, :action, auto_guard: true
The previous example is equivalent to:
guarded_attr_accessor :service, guard: :to_service
guarded_attr_accessor :icon, guard: :to_icon
guarded_attr_accessor :action, guard: :to_action
Defined Under Namespace
Modules: ClassMethods, InstanceMethods
Class Method Summary collapse
Class Method Details
.included(klass) ⇒ Object
41 42 43 44 45 46 47 48 49 |
# File 'lib/has_helpers/attributes.rb', line 41 def self.included(klass) klass.extend(ClassMethods) klass.include(InstanceMethods) klass.class_eval do ClassMethods.instance_methods.each do |method_name| private_class_method method_name end end end |