Error with Twitter gem - ruby-on-rails

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 %>

Related

Rails Elastics Search Result content URL error

I was just trying out the Elastic Search in my Rails app replacing the existing search function. Everything worked nicely but I am getting http://localhost:3000/contents/video/%23%3CElasticsearch::Model::Response::Result:0x007fe24e118f40%3E url.
in content.rb
def to_param
"#{id}/#{title.parameterize}.html"
#"#{id}-#{title.downcase.slice(0..30).gsub(/[^a-z0-9]+/i, '-')}.html"
end
and in search action
def search
if params[:q].nil?
#indexs = []
else
#indexs = Content.search params[:q]
end
and in views
<% #indexs.each do |f|%>
<%= link_to((truncate f.title, length: 60), {:controller => "contents", :action => "weblinks", :id => f.to_param}, target: "_blank") %>
<% end %>
It works fine for the default listing page, but its URL generating error in search result page. Please help,and also how to replace the {:controller => "contents", :action => "weblinks", :id => f.to_param} with weblinks_path(:format) routes
I assume you use elasticsearch gem, if so you should use records to get ActiveRecord models #indexs.records

rack-affiliates gem with localhost

I'm messing with Rack::Affiliates but I don't know if it works with the domain localhost in development environment.
1º This is my config in application.rb file:
config.middleware.use Rack::Affiliates, {:param => 'aff_id', :ttl => 6.months, :domain => '.localhost'}
2º I send a email with a link and param aff_id something like:
<%= link_to "accept invite", new_user_registration_url(:aff_id => #user.id) %>
3º In root action:
def index
if request.env['affiliate.tag'] && affiliate = User.find_by_affiliate_tag(request.env['affiliate.tag'])
logger.info "Halo, referral! You've been referred here by #{affiliate.name} from #{request.env['affiliate.from']} # #{Time.at(env['affiliate.time'])}"
else
logger.info "We're glad you found us on your own!"
end
respond_to do |format|
format.html
end
end
I'm getting the message on console:
We're glad you found us on your own!
What am I doing wrong?
Thanks!
Did you remember to include config.middleware.use Rack::Affiliates in your config/application.rb file?
If not, add it and see what happens.
Otherwise you can try debugging by changing the if statement to:
if request.env['affiliate.tag']
logger.info "request.env['affiliate.tag'] = #{request.env['affiliate.tag']}"
else
logger.info "We're glad you found us on your own!"
end
This should tell you if the affiliate.tag is getting set and if so to what value.
It's all due to User.find_by_affiliate_tag. have you any column named affiliate_tag.
If your are inviting using this link <%= link_to "accept invite", new_user_registration_url(:aff_id => #user.id) %> where you are using #user.id as aff_id.
So you have to use User.find_by_id instead of User.find_by_affiliate_tag
Final code snippet of exmaple contoller will look like
class ExampleController < ApplicationController
def index
str = if request.env['affiliate.tag'] && affiliate = User.find_by_id(request.env['affiliate.tag'])
"Halo, referral! You've been referred here by #{affiliate.name} from #{request.env['affiliate.from']} # #{Time.at(env['affiliate.time'])}"
else
"We're glad you found us on your own!"
end
render :text => str
end
end

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

Twitter gem not working from controller in 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.

How to make a POST to a third party and get the result back with Ruby on Rails?

I'm having a form in a .erb file, where the user can enter some info. Then I want to make a POST to a different URL (let's say www.3rdparty.com/api.php?f=add_entry), that will reply with 0 or 1, for success or failure. Which is the right way to go, especially if I want to stay on the page with the form, and then show a dialog according to the response? I have no experience in Ruby on Rails, so I'm not even sure if this is possible, or if I should add functionality to the controller. Thus, I would really appreciate it if you could provide beginner details :)
Thanks,
Irene
require 'net/http'
url = URI.parse('http://www.3rdparty.com/api.php?f=add_entry')
args = {'arg1' => 'data' }
response = Net::HTTP.post_form(url, args)
See:
http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
# routes.rb
map.resources :books, :member => {:status => :get}#status route member optional - see below
# book_controller.rb
def new
#book = Book.new
# new.html.erb
form_for #book, :url => books_path do |f|
<%= f.fields_for :title -%>
<%= f.fields_for :isbn -%>
#book_controller.rb
def create
#book = Book.new params[:book]
if #book.save
redirect_to status_book_path #book #optional
# no need to redirect. Create a create.html.erb and it will be rendered by default
#book.rb #model
before_create :verify_isbn
private
def verify_isbn
require 'net/http'
url = URI.parse('http://www.3rdparty.com/api.php?f=add_entry')
args = {:isbn => isbn }#here the latter isbn is a field of your model
response = Net::HTTP.post_form(url, args)
errors.add(:isbn, "That isbn is not valid") unless response.to_i == 1
end

Resources