I'm using twitter gem for Twitter API in Rails.All works properly but I'm not able to send image url and link with my post to twitter site..
Here is my code:
In Model:-
def twitter
#twitter ||= Twitter::Client.new(oauth_token: token, oauth_token_secret: secret )
end
def post_to_twitter(user)
begin
#twitter = user.authentications.find_by_provider('twitter')
if #twitter.present?
twitter = #twitter.twitter
twitter.update(self.title)
end
rescue Exception => e
Rails.logger.debug e.message
end
end
In controller:-
def create
#post = Post.new(params[:post])
#post.user_id = current_user.id
respond_to do |format|
if #post.save
#post.post_to_twitter current_user
format.js { render :layout => false }
else
#message = "Please enter content"
format.js { render :layout => false }
end
end
end
By using: twitter.update(self.title)...The title of my app goes to twitter site but how can I Send any link and image url same as title??
Make a regular POST request using AccessToken to post the links and urls- oauth rdoc.
Get the access token by Using the oauth ruby gem.
The all and all process of Getting to grips with the Ruby OAuth gem and the Twitter API.
Related
I want my app to redirect to my home page ie posts#index. It is a rails2 app which I am trying to migrate to rails 3.
def rescue_action_in_public(exception)
flash[:notice] = "There was an error. Please try again." # #{exception}
redirect_to :controller => :posts, :action => :index
end
This method I presume does this task. How ever, It won't work in rails 3 and I see the 'Sorry something went wrong!' page
How can I get this functionality working in rails 3? If any more info is, needed I am willing to paste here.
in rails 3 try this
def rescue_action_in_public(exception)
status = status_code(exception)
locale_path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html"
if locale_path && File.exist?(locale_path)
render(status, File.read(locale_path))
elsif File.exist?(path)
render(status, File.read(path))
else
render(status, '')
end
end
from apidock
You can right this way!
def rescue_action_in_public(exception)
flash[:notice] = "There was an error. Please try again." # #{exception}
redirect_to posts_path
end
I am using devise for user sign up/in. But when user signs in from public accessible pages, devise redirects to root_path.
I tried to use this:
def after_sign_in_path_for(resource)
request.referrer
end
When user tries to sign in, it gives error 'not redirected properly'.
Can anybody tell how to do it?
I believe if I am right what you want to do is override the redirect when a user sign in is to change the following method inside controllers/devise/sessions_controller.rb If you haven't generated devises controllers you generate devise controller. Having done that you will want to have something like the following inside your devise/sessions_controller.rb
def create
self.resource = warden.authenticate!(auth_options)
set_flash_message(:notice, :signed_in) if is_navigational_format?
sign_in(resource_name, resource)
# respond_with resource, :location => after_sign_in_path_for(resource)
if current_user.role? :administrator
redirect_to dashboard_path
else
redirect_to rota_days_path
end
end
In the above example by default the sessions_controller - create method uses the following: # respond_with resource, :location => after_sign_in_path_for(resource) which I have commented out. By adding a if statement that checks if the current_users role is an administrator. If they then they are redirected to the dashboard page. If not then they are redirected to the rota page.
Alternatively the devise helpers state that you could also do something like:
def after_sign_in_path_for(resource)
stored_location_for(resource) ||
if resource.is_a?(User) && resource.can_publish?
publisher_url
else
super
end
end
Hope this helps.
Update
def create
#hospital_booking = HospitalBooking.new(params[:hospital_booking])
respond_to do |format|
if #hospital_booking.save
format.html { redirect_to :back, notice: 'Photographer Shift was successfully created.' }
format.json { render json: #hospital_booking, status: :created, location: #hospital_booking }
else
format.html { render action: 'new' }
format.json { render json: #hospital_booking.errors, status: :unprocessable_entity }
end
end
end
What happens here is when the hospital_booking is saved it redirects back to the issue page instead of redirecting to another page. Further reading here: api dock- redirect_to
Sorry if this is a noob question on oauth
I've implemented an oauth2 API with devise+doorkeeper based on the examples here: https://doorkeeper-provider.herokuapp.com/ and here: https://github.com/applicake/doorkeeper-devise-client
I want to be able to provide an API endpoint that returns a list of deals that's paginatable, the code is the following:
module Api::V1
class DealsController < ApiController
doorkeeper_for :index
doorkeeper_for :create, :scopes => [:write]
respond_to :json
def index
if params[:page].nil?
page = 1
else
page = params[:page].to_i
end
respond_with Deal.page(page).order("published DESC")
end
def create
respond_with 'api_v1', Deal.create!(params[:deal])
end
end
end
However, on the client side, I cannot pass a page param with something like this:
/explore/deals.json?page=3
The page param is not seen in the provider for some reason. Can someone help me please?
I realized the problem is in the api_controller of doorkeeper-devise-client
The page param isn't passed correctly. Making the following change fixes the problem:
class ApiController < ApplicationController
respond_to :json
def explore
api_call = params[:api]
if !params[:page].nil?
api_call << "/?page=#{params[:page]}"
end
#json = doorkeeper_access_token.get("api/v1/#{api_call}").parsed
respond_with #json
end
end
I am using devise, omniauth & facebook-omniauth for my Rails 3.1 app. After authentication I wanted to redirect the user to the page was viewing. I have used the following code for the same:
def facebook
#user = Spree::User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
if #user.persisted?
flash[:notice] = "Yipee! You were successfully authorized from your Facebook account!!"
sign_in #user, :event => :authentication
redirect_to request.referrer
end
This gives me the following error only at the time of user creation:
ActionController::ActionControllerError in Spree::OmniauthCallbacksController#facebook
Cannot redirect to nil!
The following times when the user has already been created, no errors are shown during & after log in.
How do you suggest I fix this? Thanks!
you can overwrite the functions for sign in/ sign up path in your application controller:
def after_sign_up_path_for(resource)
credit_path
return request.env['omniauth.origin'] || session[:return_to]
end
def after_sign_in_path_for(resource)
return request.env['omniauth.origin'] || session[:return_to]
end
use sessions to store the current path in the path that you want them to go to: session[:return_to] = request.url #store current location
or you create a method that will always be called once they go to a path and store that location. watch out for a giant loop redirection when you do that though.
i want to rebuild an app which is a typical rails 3.2 mvc app into a API + Frontend (Backbone) only. As I have no experience in building APIs in rails including authenticatin:
What's the best way to authenticate with devise using backbone? Using auth_tokens?
How should I make he API? Just printing out JSON or use a gem like Grape?
thanks in advance!
I can explain you the way i do this :
First, i install a standard rails application with devise. After that, i create my own session controller :
class SessionsController < ApplicationController
def authenticate
# this method logs you in and returns you a single_access_token token for authentication.
#user = User.find_for_authentication(:email => params[:user][:email])
if #user && #user.valid_password?(params[:user][:password])
render :json => {:user => {:email => #user.email, :id => #user.id, :firsname => #user.firstname, :lastname => #user.lastname, :team_id => #user.team_id, :singleAccessToken => #user.generate_access_token}}
else
render :json => {:errors => ["Nom d'utilisateur ou mot de passe invalide"]}, :status => 401
end
end
end
As you can see, i send a request to this url with the json looking like :
{
user => {
email => "myemail#toto.com",
password => "monpass"
}
}
And my controller return me the json with user data if every thing is fine, or an error. On json with user, i return an access_token used on next requests to check that the user is allowed to request. I made this filters in my application controller :
class ApplicationController < ActionController::Base
protect_from_forgery
protected
def user_access_token
request.headers["HTTP_X_USER_ACCESS_TOKEN"] || request.headers["HTTP_USER_ACCESS_TOKEN"]
end
def current_user
if token = user_access_token
#user ||= User.find_by_access_token(token)
end
end
def require_user
unless current_user
render :json => {:error => "Invalid Access Token"}, :status => 401
end
end
def require_owner
unless current_user && current_user == object.user
render :json => {:error => "Unauthorized"}
end
end
end
As you can see, on each next request, i will add the access_token in html header on key : HTTP_USER_ACCESS_TOKEN
So, i can check if the user is allowed to make the request.
To make an API, you can use the Rails API gem as see here :
http://railscasts.com/episodes/348-the-rails-api-gem
Good luck.