Last active
August 29, 2015 14:15
-
-
Save edtjones/b07bd750564d8a7d459a to your computer and use it in GitHub Desktop.
contentful_model - setup and example model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'contentful' | |
require 'contentful_model' | |
#Configure your access to Contentful: demo account shown here | |
ContentfulModel.configure do |config| | |
config.access_token = "b4c0n73n7fu1" #replace with your access token | |
config.space = "cfexampleapi" #replace with your space ID | |
config.options = { | |
#extra options to send to the Contentful::Client | |
} | |
end | |
# Inherit from ContentfulModel::Base and specify a content type ID | |
# to access the attributes for your model | |
# This is your model definition. Short, isn't it? :-) | |
class Cat < ContentfulModel::Base | |
self.content_type_id = "cat" #note that your content type will actually be a long string | |
#optionally coerce fields to a particular type | |
coerce_field birthday: :date | |
end | |
# Add entry mappings for your classes, so you get objects of the type you expect | |
ContentfulModel::Base.descendents.each do |klass| | |
klass.send(:add_entry_mapping) | |
end | |
# Call your new Cat model with an ActiveRecord-like interface | |
c = Cat.first | |
# => #<Cat: @fields={:name=>"Happy Cat", etc. etc.}> | |
c.name | |
# => "Happy Cat" | |
Cat.first.birthday | |
# => Tue, 28 Oct 2003 23:00:00 +0000 | |
c.best_friend | |
# => #<Cat: @fields={:name=>"Nyan Cat", :likes=>["rainbows", "fish"], etc. etc. > | |
c.best_friend.likes | |
# => ["rainbows", "fish"] | |
Cat.offset(1).first | |
# => #<Cat: @fields={:name=>"Garfield", :likes=>["lasagna"], etc. etc. > | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment