module Tardvig::DataIdentifier
Mixin for containers which adds them ability to use “data identifier”: universal selector of data which contains in a container. It is useful in situation when you need to access data, but you can not directly get them (e. g. in client-server games).
Public Instance Methods
get_this(id)
click to toggle source
Gets an element from this container using data identifier. @param id [Symbol,String] key of the element.
It supports attributes (id `:key` for `object.key`) and the `[]` method (`:key` for `object[:key]` or `object['key']`). You can also get elements from container which is contained in this container (etc) using the `/` symbol (`foo/bar` for `object.foo.bar`).
# File lib/tardvig/data_identifier.rb, line 13 def get_this(id) obj = self id.to_s.split('/').each do |part| obj = get_elem_from_id obj, part end obj end
Private Instance Methods
get_elem_from_id(container, id)
click to toggle source
# File lib/tardvig/data_identifier.rb, line 23 def get_elem_from_id(container, id) if id.respond_to?(:to_sym) && container.respond_to?(id.to_sym) container.send id.to_sym elsif container.respond_to?(:[]) if num?(id) container[id.to_i] elsif !container.class.ancestors.include?(Array) container[id] || container[id.to_sym] end end end
num?(str)
click to toggle source
# File lib/tardvig/data_identifier.rb, line 35 def num?(str) str.to_i.to_s == str end