Object interface over remote HTML (and JSON) resources.
For example you have http://example.com/companies/a
with this content:
<html>
<body>
<h1>Company A</h1>
<div class="desc">Lovely company</div>
</body>
</html>
First, define Company model:
class Company < RemoteResource::Html::Model
attr_accessor :name, :description
mapping do |doc|
self.name = doc.c('h1')
self.description = doc.c('.desc')
end
end
Now you can make requests:
company = Company.path('http://example.com/companies/a').find
company.name # => "Company A"
company.description # => "Lovely company"
mapping
describes how to get attributes from html:
class Company < RemoteResource::Html::Model
attr_accessor :name, :description
mapping do |doc|
self.name = doc.c('h1')
self.description = doc.c('.desc')
end
mapping :fake_name do |doc|
self.name = 'Fake'
self.description = doc.c('.desc')
end
end
company = Company.path('http://example.com/companies/a').find(:fake_name)
company.name # => "Fake"
company.description # => "Lovely company"
Inside document_map you can use special helpers:
c(selector) # Get content of html node by css selector
a(attribute, selector) # Get tag attribute by css selector
parse_date(string) # Get date, uses chronic gem to parse complex dates
.find
(and its alias .first
) returns only first occurrence, meanwhile .all
returns Array of all elements.
<!-- http://example.com/companies -->
<html>
<body>
<div class="company">
<h1>Company A</h1>
<div class="desc">Lovely company</div>
</div>
<div class="company">
<h1>Company B</h1>
<div class="desc">Worst company ever</div>
</div>
</body>
</html>
Collection of companies:
companies = Company.path('http://example.com/companies').separate(css: '.company').all # => [<Company...>, <Company...>]
companies.first.name # => "Company A"
companies.last.name # => "Company B"
Pagination can be performed with multiple ways, for example:
class Company < RemoteResource::Html::Model
# ...
module RelationMethods
def page(n)
query(limit: 100, offset: n.to_i * 100)
end
end
end
Company.path('http://example.com/companies').page(0).all
# will perform request to http://example.com/companies?limit=100&offset=0
Add this line to your application's Gemfile:
gem 'remote_resource'
And then execute:
$ bundle
Or install it yourself as:
$ gem install remote_resource
TODO: Write usage instructions here
- Fork it ( https://github.com/[my-github-username]/remote_resource/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request