How can I run a Controller Action from Rails Console, but setting the request.shot? - ruby-on-rails-3

I'm working on a multi-tenant application, so pretty much everything throughout (starting with routing) expects to have a "request.host" that looks like "tenant_id.myapp.com".
I'm trying to run a controller action from the Rails console, but I haven't been able to figure this one out.
The easiest thing to do seems to be "app.get", but I can't figure out how to set the host.
I also saw an answer that mentions using "ActionController::TestProcess", which as far as I understand has been removed from Rails (or if not, I haven't found how to include it)
Any other options?
Thanks!
Daniel

I just verified it in my console(Pry)
# Send request with fake HTTP_HOST
>>app.get(app.root_path, nil, {"HTTP_HOST" => "123.myapp.com"})
>>#=>200
# Then check if it works
>>app.request.env
>>#...
>># "HTTP_HOST" : "123.myapp.com"

Related

Laravel 4: when using Config::set to change auth.model then Auth::user() not work

My laravel project has two login system.
1) Using user_name and Password
2) Using secret code
my 1st login system work properly. because auth.model has 'User' model.
so I use 'Config::set' in 'tempSing' method to obtain 2nd login as bellow.
Config::set('auth.model', 'TempUser')
Config::set('auth.table', 'temp_user')
After that code I use bellow code
$user= TempUser::where('secret_code','=',Input::get('code'))->first();
Auth::login($user,true);
if(Auth::check())
return Redirect::route('getTemp');
then that code work properly and redirect to the 'getTemp' and after routing it make 'temp.php'. but their include
if(Auth::check())
so my problem is above logic not become true. that problem is occurred when using 'Config::set' but I Configured 'auth.model' and 'auth.table' manualy in 'auth.php' not happen any error. Please help me.
I would assume Laravel initializes the Auth service once when the application is started, so later edits to configuration don't affect it anymore. A solution would be to initialize an instance yourself, and use that.

Use Ruby Extension (.bundle) in Rails Applications

I have a built a Ruby Extension for C/Objective-C and now would like to use it in a Ruby on Rails web application but everytime I try to require it, WEBrick crashes! What I have is:
I have a Ruby Class: MyRubyObject which is tied to a C class (MyExtension).
MyRubyObject has been defined with one method: myRubyMethod which is tied to a function in my C class, MyExtension: myextensionmethod which just returns a string.
myextensionmethod essentailly calls another library which performs a load of work (multiple threads and what not) but finally returns a string
after compiling everything I get a MyRubyObject.bundle file. Using IRB, I can:
require './MyRubyObject'
p = MyRubyObject.new
p.myRubyMethod
=> "Result!"
This all works absolutely fine and now I want to use it in a RoR app
I put the MyRubyObject.bundle in lib in my RoR app and then from a controller class I do a require ./lib/MyRubyObject.bundle and WEBrick crashes!!!!
Any help would be greatly appreciated!!!
Cheers
I found a solution where from here: ruby-ldap gem not work in rails3 app, but work in rails console whereby I
Put a 'require File.expand_path('../../lib/MyRubyObject', __FILE__)' in config/environment.rb file (after 'require File.expand_path('../application', __FILE__)')
Then in my controller file I just put a require 'MyRubyObject' and was then able to instantiate normally: p = MyRubyObject.new ...
So I presume this was a related issue to WEBrick loading things in an incorrect order based upon the above link but I will keep an eye on this as we'll move servers most likely and this issue may pop it's ugly head up again!
Hope this helps others!
Thanks

Debugging ActiveMerchant; need full request and response. How to?

Rails 3.0.10 and activemerchant gem 1.29.3
My app works fine in sandbox, but transactions in production mode are failing with "Security header is not valid", "ErrorCode"=>"10002"
We initiated a support request with paypal, after reviewing all the configuration parameters a million times and they feel we're hitting an incorrect endpoint. They've asked for a full trace for the transaction, including headers, etc, so I'm trying to figure out how to do that. I found this article
which suggested adding this to the config block
ActiveMerchant::Billing::PaypalGateway.wiredump_device = File.new(File.join([Rails.root, "log", "paypal.log"]), "a")
But that just results in an empty log; nothing gets dumped to it.
So, how can I obtain this info from the GATEWAY object, if possible? Here's the production config, the format of which is identical to what's used in staging env.
::GATEWAY = ActiveMerchant::Billing::PaypalGateway(
:login => 'me_api1.blah...',
:password => 'string...',
:signature => 'longer string...'
)
Thanks.
Needed to add the additional line as follows:
ActiveMerchant::Billing::PaypalGateway.wiredump_device.sync = true
Within the same config block in the environment
Somewhere in the class library you're using there should be a function to output this for you (if it's a well built library, that is.)
Even without that, though, you should be able to look in that PaypalGateway function to see where/how it's setting the endpoint. It's either hard-coding the value or it'll be setting different endpoints based on some sandbox option you have configured somewhere else in the class.
It's hard to tell you more than that without getting a look a the actual class library you're using, but I can concur that it must be either incorrect credentials or an incorrect endpoint. I've never once seen that security header error when it wasn't simply invalid credentials, which means either your values are incorrect or you're hitting the wrong endpoint.
If you want to post that whole function (or maybe even the whole library as the endpoint could be getting set from some other function) I can take a look and find the problem for you.

Raising route not found error

I'm writing a book on Rails 3 at the moment and past-me has written in Chapter 3 or so that when a specific feature is run that a routing error is generated. Now, it's unlike me to go writing things that aren't true, so I'm pretty sure this happened once in the past.
I haven't yet been able to duplicate the scenario myself, but I'm pretty confident it's one of the forgotten settings in the environment file.
To duplicate this issue:
Generate a new rails project
important: Remove the public/index.html file
Add cucumber-rails and capybara to the "test" group in your Gemfile
run bundle install
run rails g cucumber:skeleton
Generate a new feature, call it features/creating_projects.feature
Inside this feature put:
This:
Feature: Creating projects
In order to value
As a role
I want feature
Scenario: title
Given I am on the homepage
When you run this feature using bundle exec cucumber features/creating_projects.feature it should fail with a "No route matches /" error, because you didn't define the root route. However, what I and others are seeing is that it doesn't.
Now I've set a setting in test.rb that will get this exception page to show, but I would rather Rails did a hard-raise of the exception so that it showed up in Cucumber as a failing step, like I'm pretty sure it used to, rather than a passing step.
Does anybody know what could have changed since May-ish of last year for Rails to not do this? I'm pretty confident it's some setting in config/environments/test.rb, but for the life of me I cannot figure it out.
After I investigate the Rails source code, it seems like the ActionDispatch::ShowExceptions middleware that responsible of raising exception ActionController::RoutingError is missing in the test environment. Confirmed by running rake middleware and rake middleware RAILS_ENV=test.
You can see that in https://github.com/josh/rack-mount/blob/master/lib/rack/mount/route_set.rb#L152 it's returning X-Cascade => 'pass' header, and it's ActionDispatch::ShowExceptions's responsibility to pick it up (in https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/middleware/show_exceptions.rb#L52)
So the reason you're seeing that your test case is passing because rack-mount is returning "Not Found" text, with status 404.
I'll git blame people and get it fix for you. It's this conditional here: https://github.com/rails/rails/blob/master/railties/lib/rails/application.rb#L159. If the setting is true, the error got translated right but we got error page output. If it's false, then this middleware doesn't get loaded at all. Hold on ...
Update: To clearify the previous block, you're hitting the dead end here. If you're setting action_dispatch.show_exceptions to false, you'll not get that middleware loaded, resulted in the 404 error from rack-mount got rendered. Whereas if you're setting action_dispatch.show_exceptions to true, that middleware will got loaded but it will rescue the error and render a nice "exception" page for you.

Need guidance in creating Rails 3 Engine/Plugin/Gem

I need some help figuring out the best way to proceed with creating a Rails 3 engine(or plugin, and/or gem).
Apologies for the length of this question...here's part 1:
My company uses an email service provider to send all of our outbound customer emails. They have created a SOAP web service and I have incorporated it into a sample Rails 3 app. The goal of creating an app first was so that I could then take that code and turn it into a gem.
Here's some of the background: The SOAP service has 23 actions in all and, in creating my sample app, I grouped similar actions together. Some of these actions involve uploading/downloading mailing lists and HTML content via the SOAP WS and, as a result, there is a MySQL database with a few tables to store HTML content and lists as a sort of "staging area".
All in all, I have 5 models to contain the SOAP actions (they do not inherit from ActiveRecord::Base) and 3 models that interact with the MySQL database.
I also have a corresponding controller for each model and a view for each SOAP action that I used to help me test the actions as I implemented them.
So...I'm not sure where to go from here. My code needs a lot of DRY-ing up. For example, the WS requires that the user authentication info be sent in the envelope body of each request. So, that means each method in the model has the same auth info hard coded into it which is extremely repetitive; obviously I'd like for that to be cleaner. I also look back now through the code and see that the requests themselves are repetitive and could probably be consolidated.
All of that I think I can figure out on my own, but here is something that seems obvious but I can't figure out. How can I create methods that can be used in all of my models (thinking specifically of the user auth part of the equation).
Here's part 2:
My intention from the beginning has been to extract my code and package it into a gem incase any of my ESP's other clients could use it (plus I'll be using it in several different apps). However, I'd like for it to be very configurable. There should be a default minimal configuration (i.e. just models that wrap the SOAP actions) created just by adding the gem to a Gemfile. However, I'd also like for there to be some tools available (like generators or Rake tasks) to get a user started. What I have in mind is options to create migration files, models, controllers, or views (or the whole nine yards if they want).
So, here's where I'm stuck on knowing whether I should pursue the plugin or engine route. I read Jordan West's series on creating an engine and I really like the thought of that, but I'm not sure if that is the right route for me.
So if you've read this far and I haven't confused the hell out of you, I could use some guidance :)
Thanks
Let's answer your question in parts.
Part One
Ruby's flexibility means you can share code across all of your models extremely easily. Are they extending any sort of class? If they are, simply add the methods to the parent object like so:
class SOAPModel
def request(action, params)
# Request code goes in here
end
end
Then it's simply a case of calling request in your respective models. Alternatively, you could access this method statically with SOAPModel.request. It's really up to you. Otherwise, if (for some bizarre reason) you can't touch a parent object, you could define the methods dynamically:
[User, Post, Message, Comment, File].each do |model|
model.send :define_method, :request, proc { |action, params|
# Request code goes in here
}
end
It's Ruby, so there are tons of ways of doing it.
Part Two
Gems are more than flexible to handle your problem; both Rails and Rake are pretty smart and will look inside your gem (as long as it's in your environment file and Gemfile). Create a generators directory and a /name/name_generator.rb where name is the name of your generator. The just run rails g name and you're there. Same goes for Rake (tasks).
I hope that helps!