Save each email before sending rails 4 - ruby-on-rails-4

I want to keep track of all triggered emails by the application into a db table, so that i can have a log which emails are sent and to whom.
Kindly suggest me the best possible solution.

I have solved this using the following way:
created a class in lib directory
class MyProjectMailLogger
def self.delivering_email(message)
#to = message.to.to_s
#subject = message.subject.to_s
#message = message.body.to_s
EmailQueue.create!(:receipient_email => #to, :subject => #subject, :message => #message, :email_status_id => 3)
end
end
In config/initalizers/setup_mail.rb
ActionMailer::Base.register_interceptor(MyProjectMailLogger)
You might need to add the following line in the application.rb file as its not include files from lib directory:
config.autoload_paths += %W(#{config.root}/lib)
Yay!! and i logged my emails.

I am doing some research on this and it seems like https://github.com/ankane/ahoy_email is a nice gem to accomplish this. It uses an interceptor internally like the accepted answer. It also integrates with a free event tracking library that has a number of different backends. Might be something to consider if you're starting something like this today.

Related

twilio capability token generate for voice call integration issue

error: "uninitialized constant TwilioCapability"
Twilio capability token generate issue on live site and staging this is working properly.
This is my code of generate Twilio Capability token
class Twilio::TokenController < ApplicationController
skip_before_filter :verify_authenticity_token
def generate
token = ::TwilioCapability.generate("#{params[:appointment_id]}#{params[:from_type]}")
render json: { token: token }
end
end
twilocapabilty.rb file code
class TwilioCapability
def self.generate(id)
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
capability = Twilio::Util::Capability.new account_sid, auth_token
application_sid = ENV['TWIML_APPLICATION_SID']
capability.allow_client_outgoing application_sid
capability.allow_client_incoming id
capability.generate
end
end
Twilio developer evangelist here.
I believe there might be a couple of issues with this, mainly answered in this existing SO question.
Firstly, make sure that, if your class is called TwilioCapability then the file name matches it via the Rails naming rules. It should be called twilio_capability.rb.
Other than that, I guess you are keeping the file in the lib directory (so it should be lib/twilio_capability.rb). If you are not already autoloading files from lib in production, then you should add the following to your config/application.rb:
config.autoload_paths << Rails.root.join('lib')
Let me know if that helps at all.

Redirecting a request in a routing constraint

I have Sidekiq mounted in my routes file to the /sidekiq endpoint.
I use a constraints option to have it call an external class for validation as a way of preventing non-privelaged users from accessing that endpoint.
# config/routes.rb
mount Sidekiq::Web => "/sidekiq", constraints: Sidekiq::AdminConstraint.new
# lib/sidekiq/admin_constraint.rb
module Sidekiq
class AdminConstraint
def matches?(request)
return false unless request.session[:user_id]
user = User.find_by_id(request.session[:user_id])
user && Ability.new(user).can?(:manage, :sidekiq)
end
end
end
This setup works great. However, it only lets me return true / false on whether the request should go through or not. It does not let me -
Set a flash message (e.g. "You are not permitted to access that page") and
Redirect to some arbitrary page
In that sense, I'm looking for it to behave more like a controller's before_filter.
Is there a way I can modify the request object that's passed in to implement that redirect?
Thanks!
I don't have idea directly set the flash messages, But we can use in different way.
Use the following solution
In your routes.rb, add the following line in the end of the file
match "*path", :to => "application#error_404"
This basically means, any path that is not defined in your route will end up going to error_404 in application_controller. Its very important to put this at the end of your file
And in your ApplicationController, add
def error_404
redirect_to root_path
end
Thanks

In Rails4, using Trailblazer, how do I access the current_user

We are building a Rails4 app using Trailblazer. I have never worked with Trailblazer before and I am confused about how to do things.
We are building an auction site. I was previously using a traditional controller, and this route endpoint was working fine:
def bill
#profile = Profile.find_by user_id: current_user_id
#current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
#batch = #current_order.batch
if #batch.nil?
puts "There was no batch linked to the current order of #{#current_order.id}"
flash[:error] = "We are sorry, but we could not determine which batch your order belongs to."
else
#price_shown_to_customer = #batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f
#amount = #current_order.quantity * #price_shown_to_customer
end
But now I'm suppose to create this as a Trailblazer api, using a Representer class.
So in routes.rb I added something for "charges":
namespace :api do
get '/price' => 'info#info'
post '/order' => 'orders#create'
get '/charges' => 'charges#bill'
end
I created this Api but copying-and-pasting another:
module Api
class ChargesController < ApiApplicationController
respond_to :json
def bill
respond_with OpenStruct.new.extend(ChargesRepresenter)
end
end
end
I tested the above with a simple Representer and it all worked fine, so everything is good up to this point. If I return simple data from the Representer, then I can see it fine here:
http://localhost:3000/api/charges.json
But I need to get the current_user. How is this done? Right now, this does not work:
module ChargesRepresenter
include Roar::JSON
collection :price_shown_to_customer
def price_shown_to_customer
current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
puts "current_order"
puts current_order.id
batch = current_order.batch
batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f
end
end
current_user_id exists in my traditional controllers because we set up Devise and so my traditional controllers inherit it:
class ChargesController < SecuredController
But is there any way to get it in a Trailblazer Representer?
Hope this answer is not too late.
If you can switch to Decorator pattern instead of a Module.
Representer really doesn't need to know and doesn't care if it is called from controller or console or test. All it needs is a hash to build your json object from. So you can just pass another attribute called current_user_id to your Representer and then use it inside r presenter like you do.
FYI:
If you need a more immediate response you can also copy your question to https://gitter.im/trailblazer/chat . There are usually several people hanging out there. But it's also good to post a question here for posterity.

Rails: testing custom classes with RSpec

Yea, I know that this question is silly, newbee and simple, but I still can't figure it out.
I've created a class (in app/minions/ directory) to parse auth hashes from 3rd-party services (like google, twitter, etc.). It looks like this.
class AuthHash
def initialize(hash)
#hash = hash
#provider = hash[:provider]
#uid = hash[:uid]
create_user_hash
end
def create_user_hash
#user_hash = send("parse_hash_from_" << #hash[:provider], #hash)
end
def credentials
{provider: #provider, uid: #uid}
end
def user_hash
#user_hash
end
private
# parse_hash_from_* methods here
end
I've added that directory to the autoload path, so I can use it in my controllers. Now I want to write some tests for it.
I'm using RSpec with FactoryGirl for testing. So I started by adding a factory to spec/factories/ called auth_hashes.rb but I can't define a hash as a field in a factory.
So I moved the declaration to the spec/minions/auth_hash_spec.rb.
require 'spec_helper'
describe AuthHash do
before_each do
auth_hash = AuthHash.new({:provider=>"google_oauth2",:uid=>"123456789",:info=>{:name=>"JohnDoe",:email=>"john#company_name.com",:first_name=>"John",:last_name=>"Doe",:image=>"https://lh3.googleusercontent.com/url/photo.jpg"},:credentials=>{:token=>"token",:refresh_token=>"another_token",:expires_at=>1354920555,:expires=>true},:extra=>{:raw_info=>{:id=>"123456789",:email=>"user#domain.example.com",:verified_email=>true,:name=>"JohnDoe",:given_name=>"John",:family_name=>"Doe",:link=>"https://plus.google.com/123456789",:picture=>"https://lh3.googleusercontent.com/url/photo.jpg",:gender=>"male",:birthday=>"0000-06-25",:locale=>"en",:hd=>"company_name.com"}}})
end
end
But still it does not seem to work.
I know this should be alot simpler then I'm trying to do, but I can't figure it out.
Add something like this to that new spec (spec/minions/auth_hash_spec.rb) file at the top:
require Rails.root.to_s + '/app/minions/myhash.rb'
And then write your tests.

Error 404 when i use ActiveResource with Redmine

i have a problem with redmine. In fact, i've created a model who use ActiveResource :
require 'active_resource'
class New < ActiveResource::Base
#self.site = "http://localhost:3000/"
#self.format = :xml
#self.user = 'admin'
#self.password = 'admin'
class << self
attr_accessor :api_key
end
def save
prefix_options[:api_key] = self.class.api_key
super
end
end
New.site = 'http://localhost:3000'
New.api_key = '471bea6d1c4452b82b57287a281ff04392ae4118'
nw = New.new(:field_1 => 'value 1')
nw.save
# Retrieving news
news = New.find(:all)
puts news.first.title
#Retrieving an new
new = New.find(1)
puts new.description
puts new.author.name
# Creating an new
new = New.new(
:project_id => 1,
:author_id => 1,
:title => 'Annonce',
:summary => 'Annonce',
:description => 'Annonce'
)
if new.save
puts new.id
else
puts new.errors.full_messages
end
# Updating an 'new'
new = New.find(1)
new.title = 'NEW INFO '
new.save
# Deleting an new
new = New.find(1)
new.destroy
I'v an error 404 and i don't understand why:
/Users/bj/.rvm/gems/ruby-1.9.3-p429/gems/activeresource-4.0.0/lib/active_resource/connection.rb:144:in `handle_response': Failed. Response code =404. Response message = Not Found . (ActiveResource::ResourceNotFound)
PS: If i use api key or if i use self.site i've a 404 too !
Can you help me please? I tried many things but no every things doesn't works. Thanks for your answers !
The basic problem seems to be, that Redmine is not responding the way ActiveResource expects it. This could be due to changes in Rails 3, that where not properly reflected in Redmine yet.
The best option for you would maybe be dropping ActiveResource for something like httparty. You should also known, that Redmine currently only supports fetching all news (/news.json) and all news within a project (/projects/test_project/news.json). Neither fetching a single news directly nor creating or updating news is supported via the REST API.
Edit: The actual cause for the 404 in your code is due to the fact, that ActiveResource tried to POST to /news.json which is - as I have mentioned above - not supported by the REST API. If you remove the save call, you will run into another issue, where ActiveResource is not able to deserialize the response in New.find(:all). This lead me to think, that Redmine and ActiveResource are currently incompatible. Also the demo code in the Redmine wiki to create an issue, does not work for me.