How do I use ActiveResource with a custom URL scheme?

I am trying to create objects ActiveResource

for three objects in an internal application.

There are Tag

s, Tagging

s and Taggable

s:

http://tagservice/tags/:tag
http://tagservice/taggings/:id
http://tagservice/taggables/:type/:key

      

Tag

:tag

is the text of a URL-encoded literal tag. Tagging

:id

is an auto-incrementing integer. Taggable

:type

is a string. There is no finite set of taggable types - a service can support tagging something. Taggable

:key

is the identifier field that the service assigns to this type Taggable

. It could be a business value like the username emplyee or just an auto-incrementing integer.

If they were objects ActiveRecord

, I would code them something like this:

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :taggables, :through => :taggings
  def self.find_by_id(id)
    find_by_name(id)
  end
  def to_param
    CGI::escape(self.name)
  end
end

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :taggable
end

class Taggable < ActiveRecord::Base
  has_many :taggings
  has_mnay :tags, :through => :taggings
  def self.find_by_id(id)
    find_by_type_and_key(*id.split('/'))
  end
  def to_param
    "#{self.type}/#{self.key}"
  end
end

      

Does anyone know what these classes would like in ActiveResource

? Thanks!

+1


a source to share


1 answer


Are you using Rails 3.0? If so, you can now do almost the same in ActiveResource.

If not, consider trying a hyperactive resource: http://github.com/taryneast/hyperactiveresource



which I extended to make ActiveResource work in much the same way as Active Record. It supports associations like AR, although it doesn't support "through" - you might need manual code, for example for Baz, which has_many: foos ,: through =>: bars you would do:

# ugly, but does the job
def foos
  return [] unless bars.present?
  foo_set = []
  self.bars.each {|b| foo_set += b.foos }
  foo_set
end

      

+1


a source







All Articles