[![Gem Version](https://badge.fury.io/rb/wcc-contentful.svg)](https://rubygems.org/gems/wcc-contentful) [![Build Status](https://travis-ci.org/watermarkchurch/wcc-contentful.svg?branch=master)](https://travis-ci.org/watermarkchurch/wcc-contentful) [![Coverage Status](https://coveralls.io/repos/github/watermarkchurch/wcc-contentful/badge.svg?branch=master)](https://coveralls.io/github/watermarkchurch/wcc-contentful?branch=master) Full documentation: https://www.rubydoc.info/gems/wcc-contentful # WCC::Contentful ## Installation Add this line to your application's Gemfile: ```ruby gem 'wcc-contentful', require: 'wcc/contentful/rails' ``` If you're not using rails, exclude the `require:` parameter. ```ruby gem 'wcc-contentful' ``` And then execute: ``` $ bundle ``` Or install it yourself as: ``` $ gem install wcc-contentful ``` ## Configure Put this in an initializer: ```ruby # config/initializers/wcc_contentful.rb WCC::Contentful.configure do |config| config.access_token = config.space = end WCC::Contentful.init! ``` All configuration options can be found [in the rubydoc](https://www.rubydoc.info/gems/wcc-contentful/WCC/Contentful/Configuration) under {WCC::Contentful::Configuration} ## Usage ### WCC::Contentful::Model API The WCC::Contentful::Model API exposes Contentful data as a set of dynamically generated Ruby objects. These objects are based on the content types in your Contentful space. All these objects are generated by `WCC::Contentful.init!` The following examples show how to use this API to find entries of the `page` content type: ```ruby # Find objects by id WCC::Contentful::Model::Page.find('1E2ucWSdacxxf233sfa3') # => # # Find objects by field WCC::Contentful::Model::Page.find_by(slug: '/some-slug') # => # # Use operators to filter by a field # must use full notation for sys attributes (except ID) WCC::Contentful::Model::Page.find_all('sys.created_at' => { lte: Date.today }) # => [#, ... ] # Nest queries to mimick joins WCC::Contentful::Model::Page.find_by(subpages: { slug: '/some-slug' }) # => # # Pass the preview flag to use the preview client (must have set preview_token config param) preview_redirect = WCC::Contentful::Model::Redirect.find_by({ slug: 'draft-redirect' }, preview: true) # => # preview_redirect_object.href # => 'http://www.somesite.com/slug-for-redirect' ``` See the {WCC::Contentful::Model} documentation for more details. ### Store API The Store layer is used by the Model API to access Contentful data in a raw form. The Store layer returns entries as hashes parsed from JSON, conforming to the object structure returned from the Contentful CDN. The following examples show how to use the Store API to retrieve raw data from the store: ```ruby store = WCC::Contentful::Services.instance.store # => # {"sys"=> # ... # "fields"=> # ...} store.find_by(content_type: 'page', filter: { slug: '/some-slug' }) # => {"sys"=> # ... # "fields"=> # ...} query = store.find_all(content_type: 'page').eq('group', 'some-group') # => # {"sys"=> # ... # "fields"=> # ...} query.result # => # query.result.force # => [{"sys"=> ...}, {"sys"=> ...}, ...] ``` See the {WCC::Contentful::Store} documentation for more details. ### Direct CDN API (SimpleClient) The SimpleClient is the bottom layer, and is used to get raw data directly from the Contentful CDN. It handles response parsing and paging, but does not resolve links or transform the result into a Model class. The following examples show how to use the SimpleClient to retrieve data directly from the Contentful CDN: ```ruby client = WCC::Contentful::Services.instance.client # => # # "{\n \"sys\": {\n ... response.raw # => {"sys"=> # ... # "fields"=> # ...} client.asset('5FsqsbMECsM62e04U8sY4Y').raw # => {"sys"=> # ... # "fields"=> # ...} response = client.entries('fields.group' => 'some-group', 'limit' => 5) # => # 99 response.first # => {"sys"=> # ... # "fields"=> # ...} response.items => # response.items.count # Careful! This evaluates the lazy iterator and gets all pages # => 99 response.includes # => {"4xNnFJ77egkSMEogE2yISa"=> # {"sys"=> ...} # "6Fwukxxkxa6qQCC04WCaqg"=> # {"sys"=> ...} # ...} ``` The client handles Paging automatically within the lazy iterator returned by #items. This lazy iterator does not respect the `limit` param - that param is only passed through to the API to set the page size. If you truly want a limited subset of response items, use [`response.items.take(n)`](https://ruby-doc.org/core-2.5.3/Enumerable.html#method-i-take) Entries included via the `include` parameter are made available on the #includes field. This is a hash of ` => ` and makes it easy to grab links. This hash is added to lazily as you enumerate the pages. See the {WCC::Contentful::SimpleClient} documentation for more details. ### Accessing the APIs within application code The Model API is best exposed by defining your own model classes in the `app/models` directory which inherit from the WCC::Contentful models. ```ruby # app/models/page.rb class Page < WCC::Contentful::Model::Page # You can add additional methods here end # app/controllers/pages_controller.rb class PagesController < ApplicationController def show @page = Page.find_by(slug: params[:slug]) raise Exceptions::PageNotFoundError, params[:slug] unless @page end end ``` The {WCC::Contentful::Services} singleton gives access to the other configured services. You can also include the {WCC::Contentful::ServiceAccessors} concern to define these services as attributes in a class. ```ruby class MyJob < ApplicationJob include WCC::Contentful::ServiceAccessors def perform Page.find(...) store.find(...) client.entries(...) end end ``` ## Architecture ![wcc-contentful diagram](./doc/wcc-contentful.png) ## Test Helpers To use the test helpers, include the following in your rails_helper.rb: ```ruby require 'wcc/contentful/rspec' ``` This adds the following helpers to all your specs: ```ruby ## # Builds a in-memory instance of the Contentful model for the given content_type. # All attributes that are known to be required fields on the content type # will return a default value based on the field type. instance = contentful_create('my-content-type', my_field: 'some-value') # => # instance.my_field # => "some-value" instance.other_required_field # => "default-value" instance.other_optional_field # => nil instance.not_a_field # NoMethodError: undefined method `not_a_field' for # ## # Builds a rspec double of the Contentful model for the given content_type. # All attributes that are known to be required fields on the content type # will return a default value based on the field type. dbl = contentful_double('my-content-type', my_field: 'other-value') # => # dbl.my_field # => "other-value" dbl.other_optional_field # => nil dbl.not_a_field # => # received unexpected message :not_a_field with (no args) ## # Builds out a fake Contentful entry for the given content type, and then # stubs the Model API to return that content type for `.find` and `.find_by` # query methods. stubbed = contentful_stub('my-content-type', id: '1234', my_field: 'test') WCC::Contentful::Model.find('1234') == stubbed # => true MyContentType.find('1234') == stubbed # => true MyContentType.find_by(my_field: 'test') == stubbed # => true ``` ## Advanced Configuration Example Here's an example containing all the configuration options, and a sample setup for automatic deployment to Heroku. This is intended to make you aware of what is possible, and not as a general recommendation of what your setup should look like. ```ruby # config/initializers/wcc_contentful.rb WCC::Contentful.configure do |config| config.access_token = ENV['CONTENTFUL_ACCESS_TOKEN'] config.space = ENV['CONTENTFUL_SPACE_ID'] config.environment = ENV['CONTENTFUL_ENVIRONMENT'] config.preview_token = ENV['CONTENTFUL_PREVIEW_ACCESS_TOKEN'] # You may or may not want to provide this to your production server... config.management_token = ENV['CONTENTFUL_MANAGEMENT_TOKEN'] unless Rails.env.production? config.app_url = "https://#{ENV['HOSTNAME']}" config.webhook_username = 'my-app-webhook' config.webhook_password = Rails.application.secrets.webhook_password config.webhook_jobs << MyOnWebhookJob config.store = :lazy_sync, Rails.cache if Rails.env.production? # config.store = MyCustomStore.new # Use a custom Faraday connection config.connection = Faraday.new do |builder| f.request :retry f.request MyFaradayRequestAdapter.new ... end # OR implement some adapter like this to use another HTTP client config.connection = MyNetHttpAdapter.new config.update_schema_file = :never end WCC::Contentful.init! ``` For Heroku: ```yaml # Procfile web: bundle exec rails s worker: bundle exec sidekiq release: bin/release ``` ```sh # bin/release #!/bin/sh set -e echo "Migrating database..." bin/rake db:migrate echo "Migrating contentful..." migrations_to_be_run=$( ... ) # somehow figure this out node_modules/.bin/contentful-migration \ -s $CONTENTFUL_SPACE_ID -a $CONTENTFUL_MANAGEMENT_TOKEN \ -y -p "$migrations_to_be_run" echo "Updating schema file..." rake wcc_contentful:download_schema ``` All configuration options can be found [in the rubydoc](https://www.rubydoc.info/gems/wcc-contentful/WCC/Contentful/Configuration) under {WCC::Contentful::Configuration} ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/watermarkchurch/wcc-contentful. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). ## Code of Conduct Everyone interacting in the WCC::Contentful project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/watermarkchurch/wcc-contentful/blob/master/CODE_OF_CONDUCT.md).