Sha256: 6a805bd8bd3245c9deabdca8cb28d7760ecb5933f762920d4ccfc10c2c2b8a75

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

require 'version'
require 'httparty'
require 'mechanize'

class Aphro
  class ActionNotFound < Exception; end

  def self.client site
    Client.new site
  end

  class Client
    def initialize site
      @base_uri = site

      get @base_uri
    end

    def actions
      get_actions.merge post_actions
    end

    def method_missing action, *args, &block
      raise Aphro::ActionNotFound unless actions.include? action

      if get_actions.include? action
        get action, *args
      elsif post_actions.include? action
        post action, *args
      end
    end

    def attributes_for action
      unless post_actions.keys.include? action
        raise Aphro::ActionNotFound.new("Action #{action} not found at: #{page}")
      end
      form(action).fields.map &:name
    end

    private
    def get_actions
      links.inject({}) do |result, link|
        link.rel.each do |action|
          result.merge!({action.to_sym => {method: :get}})
        end
        result
      end
    end

    def form_for action
      page.forms_with(name: action.to_s).first
    end

    def post_actions
      forms.inject({}) do |result, form|
        result.merge!({form.name.to_sym => {method: :post} })
      end
    end

    def get *args
      @page = agent.get *args
    end

    def post action, params
      form = form_for(action)
      params.each do |p|
        f.fields.each
      end
      @page = agent.submit form
    end

    def agent
      agent ||= ::Mechanize.new
    end

    def page
      @page
    end

    def forms
      page.forms
    end

    def links
      page.links
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
aphro-0.0.1 lib/client/aphro.rb