lib/siren_client/entity.rb in siren_client-0.1.1 vs lib/siren_client/entity.rb in siren_client-0.2.0

- old
+ new

@@ -1,9 +1,11 @@ module SirenClient class Entity + include Enumerable + attr_accessor :href attr_reader :payload, :classes, :properties, :entities, :rels, - :links, :actions, :title, :type, :config, :href + :links, :actions, :title, :type, :config def initialize(data, config={}) @config = { format: :json }.merge config if data.class == String @@ -34,10 +36,27 @@ def each(&block) @entities.each(&block) rescue nil end + def search(criteria) + return false unless criteria + if criteria.is_a? String + return entities.select do |ent| + true if ent.classes.include?(criteria) || + ent.rels.include?(criteria) || + ent.href == criteria + end + elsif criteria.is_a? Regexp + return entities.select do |ent| + true if ent.classes.any? { |klass| criteria.match(klass) } || + ent.rels.any? { |rel| criteria.match(rel) } || + criteria.match(ent.href) + end + end + end + ### Entity sub-links only def go return if self.href.empty? self.class.new(self.href, @config) end @@ -49,19 +68,20 @@ @properties.each do |key, prop| return prop if method_str == key end # Does it match an entity sub-link's class? @entities.each do |ent| - return ent.go if ent.href && ent.classes.include?(method_str) + return ent.go if ent.href && + (ent.classes.map { |c| c.underscore }).include?(method_str.underscore) end # Does it match a link, if so traverse it and return the entity. @links.each do |key, link| - return link.go if method_str == key + return link.go if method_str == key.underscore end # Does it match an action, if so return the action. @actions.each do |key, action| - return action if method_str == key + return action if method_str == key.underscore end raise NoMethodError, 'The method does not match a property, action, or link on SirenClient::Entity.' end private @@ -88,20 +108,20 @@ link.rels.each do |rel| next if generic_rels.include?(rel) hash_rel = rel and break end # Ensure the rel name is a valid hash key - hash[hash_rel.underscore] = link + hash[hash_rel] = link hash end @actions = @payload['actions'] || [] @actions.map! do |data| Action.new(data, @config) end # Convert actions into a hash @actions = @actions.inject({}) do |hash, action| next unless action.name - hash[action.name.underscore] = action + hash[action.name] = action hash end @title = @payload['title'] || '' @type = @payload['type'] || '' # Should only be present for entity sub-links.