400 error when submitting tumblr post (ruby on rails) - 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

Related

Undefined method true for (class) mail_form gem

I am relatively new in Ruby on Rails programming, and I got this error when trying to use the mail_form gem.
The error is in the create function as can be seen
I think I got all setup the correct way:
My model is like this:
class Contact < MailForm::Base
attribute :name, :validate => :true
attribute :email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :message, :validate => :true
attribute :nickname, :captcha => :true
def headers
{
:subject => "Contact Form",
:to => "(my email)",
:from => %("#{name}" <#{email}>)
}
end
end
I don't know if matters that I'm trying to create a site with only one page, so I have the form to create a new contact in the welcome.html.erb of the pages controller, but I am defining the contact:
def welcome
#admin = Admin.find(1)
#projects = Project.all.order('created_at DESC')
#contact = Contact.new
end
Also I think that matters, that the create function (that is throwing the error) is in the contacts controller, I don't know if there was ok or it will be better at the same controller as the Contact.new (in the welcome function of pages):
def create
#contact = Contact.new(params[:contact])
#contact.request = request
if #contact.deliver
redirect_to(root_path, :notice => "Thank you for contacting me. I will reply shortly!")
else
flash.now[:error] = 'Cannot send message.'
end
end
I haven't tested in production yet, only in development maybe this won't happen in production, but I want to know why is this happening to me because I am following a tutorial of Mackenzie Child and this didn't happen to him, and we have the same code(except for the fact that I am trying to make this in only one view). I don't know if it helps, but this is what I have in my config/environments/development.rb:
config.action_mailer.delivery_method = :letter_opener
So in development I'm using the gem letter_opener for displaying the messages instead of sending mails, although this affects nothing in the error because the error was showing up way before I installed the gem.
I have searched in many places and in all the questions on stack overflow but I found nothing. If you can help me that would be grate.
Thanks.
EDIT:
I have tested in production with heroku and returns the same error :(
Ok,
I asked in the gem's github page and I could resolve the issue. It was that in the validation of the attributes on the Contact model I was declaring the :true as an object when it has to be only a boolean true (without colon before). Good to know for avoiding silly mistakes.

Rails: tumblr_client gem works in console, not in app

I'm new to Rails and have been writing a simple app to post to Tumblr. I got all my oauth stuff working, and decided to use the tumblr_client gem to facilitate posting. I can get it to post just fine through the console, but the same code does not do anything in the controller. It doesn't throw any errors, it just does nothing. Any suggestions? (I censored the blog with {blogname}, but it is correct in my code)
def post
#user = Tumblog.find_by_user_id(5)
#client = Tumblr::Client.new(:consumer_key => #key, :consumer_secret => #secret, :oauth_token => #user.oauth_token, :oauth_token_secret => #user.oauth_secret)
#client.text("{blogname}.tumblr.com", :body => "test", :state => "draft")
redirect_to "http://www.tumblr.com/blog/{blogname}/drafts"
end
It turns out that it was a conflict with my instance variable name. Changed #client to #clients and it worked just fine.

Redmine: Custom filter field for adding News

I'd like to add a custom filter field to "Add News" page in Redmine,
so that when I add a new news I could select group of users the email should be sent to.
The field itself is a list of Redmine User groups and every user is assigned to at least 1 of them.
Has anybody done this? Any suggestions would be appreciated
I've located the 3 files related to the issue:
/app/controller/news_controller.rb
/app/models/news.rb
/app/views/news/_form.html.erb
Environment:
Redmine version 2.2.1.stable.11156
Ruby version 1.8.7 (x86_64-linux)
Rails version 3.2.11
Environment production
Database adapter MySQL
Redmine plugins:
no plugin installed
So far I've done only 1 modification in Redmine, which sends added news to all registered users.
File: /app/modelsmailer.rb
Overview:
EDIT: Following your advice I moved mailer function to the controller:
def create
#news = News.new(:project => #project, :author => User.current)
#news.safe_attributes = params[:news]
#news.save_attachments(params[:attachments])
if #news.save
#news_added(#news)
if params[:group]
mail :to => GroupsUser.find(params[:group][:ids]).joins(:users).select("users.mail").compact,
:subject => "[#{#news.project.name}] #{l(:label_news)}: #{#news.title}"
else
render :new
end
end
end
But I'm getting error: NameError (uninitialized constant NewsController::GroupsUser): pointing to line
mail :to => GroupsUser.find
news_controller.rb:
def new
#news = News.new
#groups = GroupsUser.all
end
news/_form.html.erb:
<%= label_tag :group_ids "Groups"
<%= collection_select :group, :ids, #groups, :id, :name, {}, multiple: true %>
Edit:
I'm going to have to take a few guesses on what your controllers look like, but I'll give you something close. Based on the mailer function you provided, I'm assuming that was called out of the create controller after the News was saved. I would call the mail function after that. Something like this:
def create
news = News.new(params[:news]
if news.save
news_added(news)
send_mail_to_groups(params[:group][:ids]) if params[:group]
redirect_to ...
else
render :new
end
end
The mailing part should be removed from news_added
def news_added(news)
redmine_headers 'Project' => news.project.identifier
#author = news.author
message_id news
#news = news
#news_url = url_for(:controller => 'news', :action => 'show', :id => news)
end
in favor of its own new routine:
send_mail_to_users_by_group_ids(group_ids)
# Woo: Sent to all users, despite their email settings
mail :to => GroupsUser.find(group_ids).joins(:users).select("users.mail").compact,
:subject => "[#{#news.project.name}] #{l(:label_news)}: #{#news.title}"
end
You might want to add a where clause to only include active users.
I think that's about right. I'm doing it off the top of my head so there's probably a typo or error or two in there. Hopefully it points you in the right direction though.

Ruby on Rails: Send email from show page

I am a Rails noob and have a problem sending an email from a show page. There are several contact form tutorials out there but I cannot find one where I send an email from a page like a 'show' page. I have big errors in my routes I believe. In the model I state that Users have several Promotions and on the promotions show page I want to allow the current_user to send an email to #user.
here is app/mailers/quote_mailer.rb
class QuoteMailer < ActionMailer::Base
default :from => "tim#example.com"
def quote_mail(promotion)
#user = user
mail(:to => user.email, :subject => "You have an inquiry homeboy!")
end
end
In promotions_controller I put this action which I think might be wrong:
def quotedeliver
QuoteMailer.quote_mail.deliver
flash[:notice] = 'report sent!'
redirect_to root_path # or wherever
end
Here is the form that I use to send the email (the :url is probably wrong but I dont know how it should look)
<%= form_for quote_mail, :url => quotedeliver_promotion_path(promotion), :html => {:method => :put } do |f| %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
I would love some help with this. I cannot find anything like it on stackoverflow, I have been trying for days. Thank you!
You are probably missing the route in config/routes.rb
you can define it like
post '/quotedeliver_promotion' => 'promotions#quotedeliver', :as => quotedeliver_promotion
Note that quotedeliver has to be rewritten quote_deliver to follow ruby syntax conventions. When you call
QuoteMailer.quote_mail.deliver
You are not giving the parameter, so try this
QuoteMailer.quote_mail(current_user).deliver
And change your method with
def quote_mail(user)
mail ....
end
and you are all good
There are some excellent screen casts (through Railscasts) regarding sending e-mail http://railscasts.com/?tag_id=28.
One last thing, do not attach your mail sending method to a show action (if you are doing currently), the reason is show action is only for view something and users might be refreshing that page, So if you attach a mailer to that, mails might go out for each refresh.
def quote_mail(promotion)
#user = user
mail(:to => user.email, :subject => "You have an inquiry homeboy!")
end
from where you are access user variable, it should be promotion i think.

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.

Resources