Module: Structable::ClassMethods

Extended by:
Forwardable
Defined in:
lib/structable/classmethods.rb

Constructor collapse

Instance Method Summary collapse

Instance Method Details

#alias_member(aliased, original) ⇒ self


55
56
57
58
59
60
61
62
63
# File 'lib/structable/classmethods.rb', line 55

def alias_member(aliased, original)
  aliased, original = aliased.to_sym, original.to_sym
  raise "Already defined the alias '#{aliased}'" if _members[aliased]

  _members[aliased] = original

  alias_method aliased, original
  alias_method :"#{aliased}=", :"#{original}="
end

#aliasesHash


83
84
85
# File 'lib/structable/classmethods.rb', line 83

def aliases
  _members.select{|k, v|v.kind_of? Symbol}
end

#all_membersArray<Symbol>


37
38
39
# File 'lib/structable/classmethods.rb', line 37

def all_members
  _members.keys
end

#autonym(name) ⇒ Symbol


67
68
69
70
71
72
73
74
75
# File 'lib/structable/classmethods.rb', line 67

def autonym(name)
  name = name.to_sym
  
  if autonyms.include?(name)
    name
  else
    aliases[name] || raise(NameError)
  end
end

#autonymsArray<Symbol>


78
79
80
# File 'lib/structable/classmethods.rb', line 78

def autonyms
  _members.reject{|k, v|v.kind_of? Symbol}.keys
end

#each_member {|name| ... } ⇒ Enumerator Also known as: each_key

Yields:

  • (name)

Yield Parameters:

  • name (Symbol)

Yield Returns:

  • (self)

22
23
24
25
26
# File 'lib/structable/classmethods.rb', line 22

def each_member(&block)      
  return to_enum(__method__) unless block_given?
  autonyms.each(&block)
  self
end

#for_pairs(pairs) ⇒ ClassMethods Also known as: load_pairs

Returns new instance

Raises:

  • (ArgumentError)

93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/structable/classmethods.rb', line 93

def for_pairs(pairs)
  unless pairs.respond_to?(:each_pair) and pairs.respond_to?(:keys)
    raise TypeError, 'not pairs object'
  end

  raise ArgumentError, "different members" unless (pairs.keys - keys).empty?

  new.tap {|instance|
    pairs.each_pair do |name, value|
      instance[name] = value
    end
  }
end

#freezeself


112
113
114
115
# File 'lib/structable/classmethods.rb', line 112

def freeze
  close
  super
end

#has_member?(name) ⇒ Boolean Also known as: member?, has_key?, key?


44
45
46
# File 'lib/structable/classmethods.rb', line 44

def has_member?(name)
  _members.has_key? name
end

#lengthInteger Also known as: size


12
13
14
# File 'lib/structable/classmethods.rb', line 12

def length
  _members.length
end

#members(include_aliased = false) ⇒ Array<Symbol> Also known as: keys


32
33
34
# File 'lib/structable/classmethods.rb', line 32

def members(include_aliased=false)
  include_aliased ? all_members : autonyms
end