RemoteResource
Remote::Html::Model
Object interface over remote HTML (and JSON) resources.
Example
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.description
Document maps
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
company.description
Helpers
Inside document_map you can use special helpers:
c(selector)
a(attribute, selector)
parse_date(string)
Collections
.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
companies.first.name
companies.last.name
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
Installation
Add this line to your application's Gemfile:
gem 'remote_resource'
And then execute:
$ bundle
Or install it yourself as:
$ gem install remote_resource
Usage
TODO: Write usage instructions here
Contributing
- 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