Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Building API clients with Cistern

Adam Holt
February 20, 2014

Building API clients with Cistern

@nwrug - github.com/lanej/cistern

Adam Holt

February 20, 2014
Tweet

More Decks by Adam Holt

Other Decks in Programming

Transcript

  1. class Twitter::Client < Cistern::Service ! model_path "twitter/models" request_path "twitter/requests" !

    model :tweet collection :tweets request :create_tweet ! class Real def initialize(options={}) # Setup end end ! class Mock def self.data; @data ||= {}; end ! def initialize(options={}) # Setup Mock Data end end end
  2. class Twitter::Client < Cistern::Service ... ! class Real def initialize(options={})

    # Setup end end ! class Mock def self.data; @data ||= {}; end ! def initialize(options={}) # Setup Mock Data end end end
  3. class Twitter::Client::Tweet < Cistern::Model identity :id ! attribute :user, type:

    :hash attribute :tweet, type: :array ! def retweet requires :id ! new_attributes = connection.retweet_tweet(id: id).body merge_attributes(new_attributes) end end !
  4. class Twitter::Client::Tweets < Cistern::Collection ! model Twitter::Client::Tweet ! def timeline(params

    = {}) response = connection.get_tweets(params) ! data = self.clone.load(response.body) ! collection.attributes.clear collection.merge_attributes(data) end ! def retweets(params={}) response = connection.get_retweets(params) ... end ! def get(id) new(connection.get_tweet("id" => id).body) end end
  5. module Twitter class Client class Real def create_tweet(options={}) request( :body

    => {status: options[:body]}, :method => :post, :path => '/statuses/update' ) end end # Real ! ... end # Client end # Twitter
  6. module Twitter class Client ... ! class Mock def create_tweet(options={})

    id = Foo.random_hex(6) ! tweet = { "id" => id, "text" => "Hello from @NWRUG", "user" => {"name": "omgitsads"}, }.merge(options) ! self.data[:tweets][id]= tweet ! response( :body => tweet, :status => 200, :path => '/statuses/user_timeline.json', ) end end # Mock end # Client end # Twitter