This is an example from the blog post: http://www.ngauthier.com/2011/09/using-exceptions-to-manage-control-flow.html.
Please fork it and show me what you would do!
This is an example from the blog post: http://www.ngauthier.com/2011/09/using-exceptions-to-manage-control-flow.html.
Please fork it and show me what you would do!
| class TwitterReverseAuthController < ApplicationController | |
| class OauthCredential < Struct.new(:token, :secret) | |
| end | |
| class TwitterAuthenticator | |
| Error = Class.new(StandardError) | |
| def initialize(options) | |
| @options = options | |
| end | |
| def authenticate_device | |
| user.devices.find_or_create_by_token!({ | |
| :token => oauth_credential.token, | |
| :description => @options[:description] | |
| }) | |
| end | |
| private | |
| def user | |
| @user ||= User.find_for_oauth!(fetch_option(:screen_name), oauth_credential) | |
| end | |
| def oauth_credential | |
| @oauth_credential ||= OauthCredential.new(fetch_option(:oauth_token), fetch_option(:oauth_secret)) | |
| end | |
| def fetch_option(name) | |
| @options.fetch(name) { raise ArgumentError, "#{name} is required" } | |
| end | |
| end | |
| def api_key_exchange | |
| authenticator = TwitterAuthenticator.new(params) | |
| if (device = authenticator.authenticate_device) | |
| render :json => { :api_key => device.api_key } | |
| else | |
| render :json => { :errors => authenticator.errrors }, :status => :unprocessable_entity | |
| end | |
| end | |
| end |
I much prefer James's ActiveModel::Validation extraction:
https://gist.github.com/1243758