Skip to content

Instantly share code, notes, and snippets.

@rafaelp
Last active December 20, 2015 00:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rafaelp/6046165 to your computer and use it in GitHub Desktop.
Save rafaelp/6046165 to your computer and use it in GitHub Desktop.
DRAFT WORK! Wrapper for BankBillet model on Cobre Gratis API: https://github.com/BielSystems/cobregratis-api/blob/master/resources/bank_billets.md
class BankBillet
include HTTParty
include Virtus
base_uri 'https://app.cobregratis.com.br'
attribute :id, Integer
attribute :name, String
attribute :amount, Float
attribute :expire_at, Date
attribute :external_link, String
def self.create(attributes = {})
@response = post('/bank_billets.json', { :body => {bank_billet: attributes}, :basic_auth => {:username => ENV['COBREGRATIS_TOKEN'], :password => 'X'} })
return false unless @response.code == 201
new(JSON.parse(@response.body)["bank_billet"])
end
end
@rafaelp
Copy link
Author

rafaelp commented Jul 20, 2013

@tapajos Minha dúvida é: devo escrever aqui todos os atributos deste modelo usando o Virtus? O Active Model você usa para fazer as validações?

@tapajos
Copy link

tapajos commented Jul 21, 2013

Rafa,

Você precisa manter sincronizado os atributos que você recebe da API e os atributos do Virtus. Para fazer isso eu uso:

def update_virtus_attributes(remote_params)
  self.attributes = Hash[remote_params.map {|k,v| [k.to_s, v]}]
end

Eu uso o Active Model para fazer as validações e outras coisas como serialização e preparar o form para usar na view.

Esse é um exemplo simples de um modelo usando tudo isso.

class User
  include Virtus

  attribute :name, String
  attribute :age, Integer
  attribute :birthday, DateTime

  extend ActiveModel::Naming
  include ActiveModel::Validations
  include ActiveModel::Serialization
  include ActiveModel::Conversion

  validates_presence_of :name

  def update_virtus_attributes(remote_params)
    self.attributes = Hash[remote_params.map {|k,v| [k.to_s, v]}]
  end

end

Isso responde as suas perguntas? Se tiver alguma outra dúvida é só perguntar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment