1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
module Virtus
class Attribute
# Accessor extension provides methods to read and write attributes
#
# @example
#
# attribute = Virtus::Attribute.build(String, :name => :email)
# model = Class.new { attr_reader :email }
# object = model.new
#
# attribute.set(object, 'jane@doe.com')
# attribute.get(object) # => 'jane@doe.com'
#
module Accessor
# Return name of this accessor attribute
#
# @return [Symbol]
#
# @api public
attr_reader :name
# Return instance_variable_name used by this accessor
#
# @api private
attr_reader :instance_variable_name
# @api private
def self.extended(descendant)
super
name = descendant.options.fetch(:name).to_sym
descendant.instance_variable_set('@name', name)
descendant.instance_variable_set('@instance_variable_name', "@#{name}")
end
# Return if attribute value is defined
#
# @param [Object] instance
#
# @return [Boolean]
#
# @api public
def defined?(instance)
instance.instance_variable_defined?(instance_variable_name)
end
# Return value of the attribute
#
# @param [Object] instance
#
# @return [Object]
#
# @api public
def get(instance)
instance.instance_variable_get(instance_variable_name)
end
# Set value of the attribute
#
# @param [Object] instance
# @param [Object] value
#
# @return [Object] value that was set
#
# @api public
def set(instance, value)
instance.instance_variable_set(instance_variable_name, value)
end
# Set default value
#
# @param [Object] instance
#
# @return [Object] value that was set
#
# @api public
def set_default_value(instance)
set(instance, default_value.call(instance, self))
end
# Returns a Boolean indicating whether the reader method is public
#
# @return [Boolean]
#
# @api private
def public_reader?
options[:reader] == :public
end
# Returns a Boolean indicating whether the writer method is public
#
# @return [Boolean]
#
# @api private
def public_writer?
options[:writer] == :public
end
end # Accessor
end # Attribute
end # Virtus
|