Created — forked from reagent/credential.rb

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Sample code from my Using OO to Manage Control Flow post

View credential.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
class Credential
include ActiveModel::Validations
 
attr_accessor :screen_name, :oauth_token, :oauth_secret, :token, :description
 
validates_presence_of :screen_name, :oauth_token, :oauth_secret, :message => 'required'
validate :user_exists, :unless => :errors?
 
def initialize(attributes = {})
attributes.each {|k, v| set_recognized_attribute(k, v) }
end
 
def save
valid? && create_device
end
 
def as_json(options = {})
{:api_key => @device.api_key}
end
 
private
 
def errors?
errors.any?
end
 
def set_recognized_attribute(name, value)
setter_method = "#{name}="
self.send(setter_method, value) if respond_to?(setter_method)
end
 
def user
@user ||= User.by_screen_name(screen_name).where({
:oauth_token => oauth_token,
:oauth_secret => oauth_secret
}).first
end
 
def create_device
@device = Device.find_or_create_by_token!({
:token => token,
:description => description,
:user_id => user.id
})
!@device.nil?
end
 
def user_exists
errors.add(:user, 'not found') unless user.present?
end
 
end
View credential.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class CredentialsController < ApplicationController
def create
credential = Credential.new(params)
if credential.save
render :json => credential
else
render :json => {:error => errors_for(credential)}, :status => :unprocessable_entity
end
end
 
private
 
def errors_for(object)
object.errors.map {|k, m| "#{k} #{m}" }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.