Twitter gem not working from controller in Rails - ruby-on-rails

I've been using the Twitter gem in my latest Rails app, and so far have had no problems. I've registered the app, have set the API tokens in config/initializers/twitter.rb, and have tested that it works in a custom rake test that requires the gem. The problem, however, is that when I try to send a tweet form a controller, nothing happens. My initializer looks like so:
require 'twitter'
Twitter.configure do |config|
config.consumer_key = '###'
config.consumer_secret = '###'
config.oauth_token = '###'
config.oauth_token_secret = '###'
end
The ### are filled in correctly in my app, obviously. In my rake file, I require the gem at the top of the file, and am then able to send a test tweet with Twitter.update(tweet) however, the same syntax does not work from my controllers.
What am I doing wrong here? Do I need to re-initialize the gem from the controller?

After some tinkering, this is the simple solution:
#twitter = Twitter::Client.new
#twitter.update(tweet)
Adding that to my controller method worked perfectly, since the Twitter client had already been authenticated when the app started. This is the app sending out tweets, by the way, not users sending tweets through the app, so I didn't need to re-authenticate.

I am also using the Twitter gem and I use and authorizations controller for my oath, direct messages controller for Twitter DMs, and ajax on the front. The AppConfig is just a yml file that has my creds in it.
authorizations_controller.rb
class AuthorizationsController < ApplicationController
def new
set_oauth
render :update do |page|
page.redirect_to #oauth.request_token.authorize_url
end
end
def show
#oauth ||= Twitter::OAuth.new(AppConfig['consumer']['token'], AppConfig['consumer']['secret'])
#oauth.authorize_from_request(session['rtoken'], session['rsecret'], params[:oauth_verifier])
session['rtoken'] = nil
session['rsecret'] = nil
session['atoken'] = #oauth.access_token.token
session['asecret'] = #oauth.access_token.secret
redirect_path = session['admin'] ? admin_tweets_path : root_path
redirect_to redirect_path
end
end
direct_messages_controller.rb
class DirectMessagesController < ApplicationController
before_filter :authorize
def create
#client.update("##{AppConfig['user']} #{params[:tweet][:text]}")
render :update do |page|
page.replace_html 'tweet_update', "Your tweet has been sent to #{AppConfig['user']} and should be updated momentarily."
end
end
end
view.html.haml
#tweet_update
- form_remote_tag :url => direct_messages_url, :method => :post, :loading => "$('tweet_update').hide();$('loading').show()", :complete => "$('tweet_update').show();$('loading').hide()" do
%div{:class => "subheader float_left"}Tweet to Whoever
- if session_set?
%input{:type => "image", :src=>"/images/sendButton.jpg", :class =>"float_right", :style=>"margin-bottom: 4px"}
- else
%div{:class => "float_right", :id => "twitter_login_button"}= link_to_remote image_tag('twitter-darker.png'), :url => new_authorization_url, :method => :get
.float_clear
#tweetbox_bg
- textarea_options = {:id => "tweetbox", :style => "overflow: auto", :rows => "", :cols => ""}
- textarea_value = nil
- unless session_set?
- textarea_options.merge!(:disabled => "disabled")
- textarea_value = "Please login to tweet Whoever!"
= text_area_tag 'tweet[text]', textarea_value, textarea_options
My before filter 'authorize' just checks session:
def authorize
session_set? ? set_client : redirect_to(new_authorization_url)
end
Hope this helps.

Related

Devise invitation generate accept_invitation_url

I'm using Devise invitable for invitation. Typically, in the invitation email there will be a link to redirect the invitee to the sign_in page, some url like this
mywebsite.com/users/invitation/accept?invitation_token=J-azZ8fKtkuAyp2VZWQX
This url comes from invitation_instructions.html:
<p><%= link_to 'Accept invitation', accept_invitation_url(#resource, :invitation_token => #token) %></p>
Now I want to return the invitation url in my controller as json response, something like this:
def invite
invitee = User.invite!({:email => email}, current_user)
accept_invitation_url = ....
render :json => accept_invitation_url
end
any idea how to get the accept_invitation_url in the controller? Thanks!
try to include the url helpers module in your controller:
class MyController < ApplicationController
include DeviseInvitable::Controllers::UrlHelpers
def invite
invitee = User.invite!({:email => email}, current_user)
render :json => accept_invitation_url(invitee, :invitation_token => invitee.token)
end
end
The URL Helper module for the Devise Invitable Gem can be found here on github
Ok the raw invitation token is not accessible by default because it's a instance variable without accessor (source), there are two ways you could solve this.
The ugly way, without modifying your model class:
def invite
invitee = User.invite!({:email => email}, current_user)
raw_token = invitee.instance_variable_get(:#raw_invitation_token)
render :json => accept_invitation_url(invitee, :invitation_token => raw_token)
end
The clean way, by adding an attribute reader to your user model class:
# User Model
class User < ActiveRecord::Base
attr_reader :raw_invitation_token
# rest of the code
end
# In your controller
def invite
invitee = User.invite!({:email => email}, current_user)
raw_token = invitee.raw_invitation_token
render :json => accept_invitation_url(invitee, :invitation_token => raw_token)
end
Update (16th October 2015):
It seems like the UrlHelper module has been removed and the invitation is handled as a normal route, so you can remove the include DeviseInvitable::Controllers::UrlHelpers and replace the accept_invitation_url call with:
Rails.application.routes.url_helpers.accept_invitation_url(invitee, :invitation_token => raw_token)
I found out that to use accept_invitation_url outside the standard invitation mailer view you need to include inside the mailer the following helper:
include Devise::Controllers::UrlHelpers
I tried Rails.application.routes.url_helpers.accept_invitation_url(invitee, :invitation_token => raw_token) but it is not working.

Define Controller for the custom action doesnot seem to work Rails Admin

HI Everyone ,
I have rails admin implemented in my project Now there are couple of thing that I currently stuck at
I want a link (Mark as Publisher) In the list View of my user Controller in the rails admin as ajax link something that is done using remote => true in rails after that where the write the associated jscode and html code for it
for the above custom action "mark_as_publisher" I define the configuration setting like this
Inside config/rails_admin.rb
config.actions do
# root actions
dashboard # mandatory
# collection actions
index # mandatory
new
export
history_index
bulk_delete
# member actions
show
edit
delete
history_show
show_in_app
member :mark_as_publisher
end
Now The Definition of the custom action look like this
require "rails_admin_mark_as_publisher/engine"
module RailsAdminMarkAsPublisher
end
require 'rails_admin/config/actions'
module RailsAdmin
module Config
module Actions
class MarkAsPublihser < Base
RailsAdmin::Config::Actions.register(self)
register_instance_option :collection do
true
end
register_instance_option :http_methods do
[:get,:post]
end
register_instance_option :route_fragment do
'mark_as_publisher'
end
register_instance_option :controller do
Proc.new do
binding.pry
if request.get?
respond_to do |format|
format.html { render #action.template_name}
end
elsif request.post?
redirect_path = nil
if #object.update_attributes(:manager => true)
flash[:success] = t("admin.flash.successful", :name => #model_config.label, :action => t("admin.actions.mark_as_publisher.done"))
redirect_path = index_path
else
flash[:error] = t("admin.flash.error", :name => #model_config.label, :action => t("admin.actions.mark_as_publisher.done"))
redirect_path = back_or_index
end
end
end
end
end
end
end
end
Now the View for the same define in app/view/rails_admin/main/mark_as_publisher.erb look like this
<%= rails_admin_form_for #object, :url => mark_as_publisher_path(:model_name => #abstract_model.to_param, :id => #object.id), :as => #abstract_model.param_key,:method => :post ,:html => { :class => "form-horizontal denser", :data => { :title => "Mark" } } do |form| %>
<%= form.submit "save" %>
<%end%>
The get and post url for mark_as_publisher does come under by controller define above and saving the above form result in error called
could not find routes for '/user/5/mark_as_publisher' :method => "post"
Does Any body has an idea of what I'm missing
Sorry for the delayed reply, but I also came into the exact same issue.
EDIT: I notice you already have this, have you tried restarting your server?
if you add the following it will fix it.
register_instance_option :http_methods do
[:get,:post]
end
The problem is by default Actions only respond to the :get requests.
If you run
rake routes
You will see something along the lines of
mark_as_publisher_path GET /:model_name/:id/mark_as_publisher(.:format) rails_admin/main#mark_as_publisher
https://github.com/sferik/rails_admin/blob/master/lib/rails_admin/config/actions/base.rb#L89

Paypal Express Checkout in Rails3

This issue is about: ActiveMerchant + PaypalExpressCheckout + Rails 3.2
I've been trying to build a Paypal Express Checkout on my Rails 3.2 app. Most of the tutorials out there are outdated so I followed a few then read the Paypal Express Checkout integration guide. I've already set up my Sandobx and my paypal informations.
When I try to process the payment by clicking on my "Buy now" link from my view:
<%= link_to image_tag('http://img36.imageshack.us/img36/249/buttonpaypal.png'),
action: 'checkout', controller: 'orders'%>
I am getting the following error:
This transaction is invalid. Please return to the recipient's website to complete
you transaction using their regular checkout flow.
Return to merchant
At this time, we are unable to process your request. Please return to and try
another option.
--- My Controller:
class OrdersController < ApplicationController
include ActiveMerchant::Billing
def checkout
setup_response = ::GATEWAY.setup_purchase(2000,
:ip => request.remote_ip,
:return_url => url_for('confirm'),
:cancel_return_url => url_for(root_path)
)
redirect_to ::GATEWAY.redirect_url_for(setup_response.token)
end
end
--- My Initializer ActiveMerchant.rb:
ActiveMerchant::Billing::Base.mode = :test
::GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(
:login => "I_PUT_MY_EMAIL_HERE",
:password => "I_PUT_MY_PASS_HERE",
:signature => "I_PUT_MY_SIGNATURE_HERE",
:allow_guest_checkout => true
)
--- My routes: routes.rb:
resources :orders do
# Im not sure why 'get :checkout' by itself doesn't work.
get :checkout, :on => :new
get :confirm
get :complete
end
get "pages/index"
This is the gist: https://gist.github.com/11be6cef6a97632343b9
Can anyone point me to a 'recent' tutorial or help me figure out what I am doing wrong here?
The easiest way is to do as follow:
1.) You must create a paypal test account.
2.) Create a Cart Model:
$ rails g model Cart purchased_at:datetime
3.) In your Cart Model Type:
class Cart < ActiveRecord::Base
def paypal_url(return_url)
values = {
# get it form your http://sandbox.paypal.com account
:business => 'ENTER_THE_SELLER_PAYPAL_EMAIL_ADDRESS',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => id
}
# These values set up the details for the item on paypal.
values.merge!({
# The amount is in cents
"amount_1" => ENTER_AN_AMOUNT_HERE,
"item_name_1" => ENTER_THE_ITEM_NAME_HERE,
"item_number_1" => 1,
"quantity_1" => 1
})
"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
end
end
4.) On the appllication_controller.rb file add this
def current_cart
session[:cart_id] ||= Cart.create!.id
#current_cart ||= Cart.find(session[:cart_id])
end
5.) On your the view where you want the checkout button add this:
# 'products_url' is just the url where you would like to redirect
# the user after the transaction
<%= link_to 'Buy with PAYPAL', #cart.paypal_url(products_url) %>
6.) On the controller show action of the view where you want the checkout add this:
def show
...
#cart = current_cart
end
Thats it! This is a PaypalExpressCheckout without a 'real' Cart since I built this Cart without using a Line Item. But you could add a Line Item to it following the Railscast #141 Paypal Basics http://railscasts.com/episodes/141-paypal-basics
There's a recent tutorial here: http://spin.atomicobject.com/2011/10/24/integrating-paypal-express-with-rails-3-1-part-1/.

Error with Twitter gem

I'm trying to make a twitter web app on rails that can post and search for keywords and I can't figure out why it's not working, I've changed a thousand things and got a thousand different errors, this is my controller file
def hello
#time = Time.now
def user_tweet
require "rubygems"
require "twitter"
# Certain methods require authentication. To get your Twitter OAuth credentials,
# register an app at http://dev.twitter.com/apps
Twitter.configure do |config|
config.consumer_key = 'xxxx'
config.consumer_secret = 'xxxx'
config.oauth_token = 'xxxx'
config.oauth_token_secret = 'xxxx'
end
# Initialize your Twitter client
client = Twitter::Client.new
# Post a status update
client.update("updated tweet")
redirect_to request.referer, :notice => 'Tweet successfully posted'
end
end
and this is my view page
<%= form_for (#tweet = Tweet.new, :url => user_tweet_path) do |tweet_form|
tweet_form.text_area :tweet_content, :id => "tweet"
tweet_form.submit "Tweet"
end %>
Finally, here's the error I'm getting:
syntax error, unexpected ',', expecting ')'
I tried just putting <%= client.update("updated tweet")%> in the view file but it raised an undefined variable error, I'm new to rails, so any help would be appreciated, thanks.
For style, close your ERB tags after every line, don't put spaces after parentheses (like the form_for above) and don't assing values to #tweet (you don't need it):
<%= form_for(Tweet.new, :url => user_tweet_path) do |tweet_form| %>
<%= tweet_form.text_area :tweet_content, :id => "tweet" %>
<%= tweet_form.submit "Tweet" %>
<% end %>

400 error when submitting tumblr post (ruby on rails)

I am having a bit of an issue with getting tumblr working within a rails app.
This is the snippet of code which results in a 400 error (meaning that there was an incorrect parameter)
#postcontent = #post.content.gsub(/<\/?[^>]*>/, "")
post = Tumblr::Post.create(:email => 'valid#email', :password => 'mypassword', :type => 'video', :embed
=> #post.video_html, :caption => #postcontent)
I have checked the API docs and checked my code and code content being rendered, and it still does not want to work.
The funny thing is that it worked previously. It was working about a week ago. Has something changed with tumblr?
Update: I have also posted this on github in the issues section, and discovered that it's only with one of my posts that this method is not working, AND I have sent it over to the good people at tumblr. Has anyone else had this issue?
I HAVE WORKED THIS OUT ...
for anyone finding difficulty in this here is a solution.
Firstly, there was an error with the gem itself. Some code needs to be modified.
Check out this version of the gem:
http://github.com/mindreframer/tumblr
Secondly, as Tumblr allows html, I am calling sanitize within the controller to make my content nicely formatted and clean.
class PostsController < ApplicationController
include ActionView::Helpers::TextHelper
include ActionView::Helpers::SanitizeHelper
def tumblrsubmit
tumblruser = Tumblr::User.new('valid#email', 'validpass', false)
Tumblr.blog = 'blogname'
#post = Post.find(params[:id])
begin
unless #post.movie_id.nil? #checks if there is a movie ID
#tags = #post.tags.join(', ')
post = Tumblr::Post.create(tumblruser,
:type => 'video',
:embed => #post.video_html , #fetches the stored embed code
:caption => "Read Full Article & More at: <a href='http://www.mywebsite.com/posts/#{#post.slug}'>#{#post.title}</a> <p> </p>#{ActionController::Base.helpers.sanitize(#post.content)}",
:slug => #post.slug,
:tags => #tags )
else
post = Tumblr::Post.create(:tumblruser, :type => 'regular', :title => #post.title, :body => ActionController::Base.helpers.sanitize(#post.content), :slug => #post.slug)
end
#post.update_attributes(:tumbler_id => "#{post}") #updates the database with the new tumblr post id
flash[:notice] = "Successfully sent <strong>#{#post.title}</strong> to tumblr. with post id = #{post}"
rescue
flash[:error] = "You are unable to post <strong>#{#post.title}</strong> to tumblr at this time"
end
redirect_to :back
end
end
I know this seems like alot, but it does the job.
Hope this helps anyone else out there.
Cheers,
Matenia

Resources