Class: Struct

Inherits:
Object show all
Defined in:
lib/ramaze/snippets/struct/fill.rb,
lib/ramaze/snippets/struct/values_at.rb

Overview

Extensions for Struct

Direct Known Subclasses

MOFile::Header, Action

Defined Under Namespace

Classes: Action

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.fill(hash = {}) ⇒ Object

Action = Struct.new(‘Action’, :template, :method, :params)

a = Action.fill(:template => nil, :method => :meth, :params => [1]) # => #<struct Struct::Action template=nil, method=:meth, params=>



13
14
15
16
17
18
19
20
21
22
# File 'lib/ramaze/snippets/struct/fill.rb', line 13

def self.fill(hash = {})
  instance = new
  to_s = members.first.respond_to?(:to_str)
  hash.each do |key, value|
    key = to_s ? key.to_s : key.to_sym
    next unless members.include?(key)
    instance.send("#{key}=", value)
  end
  instance
end

Instance Method Details

#values_at(*keys) ⇒ Object

Example:

Point = Struct.new(:x, :y)
point = Point.new(15, 10)
point.values_at(:y, :x)
# => [10, 15]
point.values_at(0, 1)
# => [15, 10]


17
18
19
20
21
22
23
# File 'lib/ramaze/snippets/struct/values_at.rb', line 17

def values_at(*keys)
  if keys.all?{|key| key.respond_to?(:to_int) and not key.is_a?(Symbol) }
    keys.map{|key| values[key.to_int] }
  else
    keys.map{|k| self[k] }
  end
end