Class: SimpleEnum::Accessors::Accessor

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_enum/accessors/accessor.rb

Direct Known Subclasses

IgnoreAccessor, WhinyAccessor

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, enum, source = nil, prefix = nil) ⇒ Accessor

Returns a new instance of Accessor.



6
7
8
9
10
11
# File 'lib/simple_enum/accessors/accessor.rb', line 6

def initialize(name, enum, source = nil, prefix = nil)
  @name = name.to_s
  @enum = enum
  @source = source.to_s.presence || "#{name}#{SimpleEnum.suffix}"
  @prefix = prefix
end

Instance Attribute Details

#enumObject (readonly)

Returns the value of attribute enum.



4
5
6
# File 'lib/simple_enum/accessors/accessor.rb', line 4

def enum
  @enum
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/simple_enum/accessors/accessor.rb', line 4

def name
  @name
end

#sourceObject (readonly)

Returns the value of attribute source.



4
5
6
# File 'lib/simple_enum/accessors/accessor.rb', line 4

def source
  @source
end

Instance Method Details

#changed?(object) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/simple_enum/accessors/accessor.rb', line 31

def changed?(object)
  object.send(:attribute_changed?, source)
end

#prefixObject



13
14
15
# File 'lib/simple_enum/accessors/accessor.rb', line 13

def prefix
  @cached_prefix ||= @prefix && "#{@prefix == true ? name : @prefix}_" || ""
end

#read(object) ⇒ Object



17
18
19
# File 'lib/simple_enum/accessors/accessor.rb', line 17

def read(object)
  enum.key(read_before_type_cast(object))
end

#scope(relation, value) ⇒ Object



41
42
43
# File 'lib/simple_enum/accessors/accessor.rb', line 41

def scope(relation, value)
  relation.where(source => value)
end

#selected?(object, key = nil) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
# File 'lib/simple_enum/accessors/accessor.rb', line 25

def selected?(object, key = nil)
  current = read_before_type_cast(object)
  return current && current == enum[key] if key
  current
end

#to_sObject



45
46
47
# File 'lib/simple_enum/accessors/accessor.rb', line 45

def to_s
  name
end

#was(object) ⇒ Object



35
36
37
38
39
# File 'lib/simple_enum/accessors/accessor.rb', line 35

def was(object)
  changes = object.send(:changed_attributes)
  key = changes.fetch(source, read_before_type_cast(object))
  enum.key(key) if key
end

#write(object, key) ⇒ Object



21
22
23
# File 'lib/simple_enum/accessors/accessor.rb', line 21

def write(object, key)
  write_after_type_cast(object, enum[key]) && key
end