Class: Freesound::Resources::Base

Inherits:
ActiveResource::Base
  • Object
show all
Defined in:
lib/freesound/resources.rb

Direct Known Subclasses

Pack, Sound, User

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}, *args) ⇒ Base

Certain resource attributes contain dashes rather than underscores. This override allows resources with attributes like “preview-hq-mp3” to respond to “preview_hq_mp3” instead.



66
67
68
69
70
71
72
# File 'lib/freesound/resources.rb', line 66

def initialize(attributes={}, *args)
  underscored = attributes.inject({}) do |acc, (attr, value)|
    acc.merge(attr.to_s.underscore => value)
  end

  super(underscored, *args)
end

Class Method Details

.element_path(id, *args) ⇒ Object

The Freesound API requires URLs to have a trailing slash before their query parameters, otherwise the request will result in a redirect.

These are hacks to construct the URLs correctly because ActiveResource does not append a trailing slash.



19
20
21
# File 'lib/freesound/resources.rb', line 19

def element_path(id, *args)
  super("#{id}/", *args)
end

.get(path, *args) ⇒ Object



23
24
25
# File 'lib/freesound/resources.rb', line 23

def get(path, *args)
  super("#{path}/", *args)
end

.references(collection_name) ⇒ Object

Macro for establishing relationships.

Resources return has_many relationships as a URL, rather than a collection of objects. For example user JSON would look like:

{
  username: "alexgenco",
  sounds: "http://www.freesound.org/api/people/alexgenco/sounds/"
}

This macro generates methods to access these child resources by following the URL and instantiating the appropriate resource.

To setup a User that has many sounds:

class User
  references :sounds
end


46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/freesound/resources.rb', line 46

def references(collection_name)
  resource_class = collection_name.to_s.singularize.camelize

  class_eval(<<-RUBY, __FILE__, __LINE__)
    def #{collection_name}(refresh=false)
      @#{collection_name} = nil if refresh

      @#{collection_name} ||= begin
        path = URI.parse(super).path
        #{resource_class}.find(:all, from: path, params: query_params)
      end
    end
  RUBY
end