rails-translate-routes gem: Is it possible to translate routes but keep (some) original ones? - ruby-on-rails-3

I'm using rails-translate-routes gem to translate "front" routes only.
I'm using carrierwave to upload some files in my admin. Here's an uploader:
class CheatsheetUploader < CarrierWave::Uploader::Base
[...]
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
[...]
end
As you see, the path is using the name of the model and the name of the field.
When I try to get the file:
link_to "my file", download.cheatsheet.url
The path is the default one:
http://localhost:3000/uploads/download/cheatsheet/1/a_really_nice_file.pdf
And Rails give me a nice Routing error:
No route matches [GET] "/uploads/download/cheatsheet/1/a_really_nice_file.pdf"
Any way to handle this?

You can pass keep_untranslated_routes: true in your call to ActionDispatch::Routing::Translator.translate_from_file.
For example:
ActionDispatch::Routing::Translator.translate_from_file(
'config/locales/routes.yml',
no_prefixes: true,
keep_untranslated_routes: true)

Related

Image invalid on facebook/twitter user image uploading to S3

I'm trying to upload to amazon s3 an existing image on facebook or twitter from an user that has just signed up in my application, but some validation don't let me save the user object, throws: Image is invalid. I thought that was for my extension_white_list but I removed it and it's keeping saying Image is invalid.
This it's not an error, it's just a message from a validation on carrierwave I think, even if the image url string is correct.
AvatarUploader
# encoding: utf-8
class AvatarUploader < CarrierWave::Uploader::Base
include CarrierWaveDirect::Uploader
include CarrierWave::RMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
include CarrierWave::MimeTypes
process :set_content_type
def store_dir
"avatar/#{model.id}"
end
version :thumb do
process resize_to_fill: [50, 50]
end
# def extension_white_list
# %w(jpg jpeg gif png bmp)
# end
end
Creating user:
...
new_user = User.create( :name => auth['info']['name'],
:email => User.email_from_auth(auth) )
auth_image_url = Authentication.larger_image(auth) # a string of user image url from social network authentication data. ie: http://a0.twimg.com/profile_images/1255111511/skyline.jpg
unless auth_image_url.blank?
new_user.remote_image_url = auth_image_url
new_user.save
end
...
Fixed! The error has nothing to do with carrierwave, just the fact that the object does not exist on database in the moment where the image is upload, first I save the new user and then:
after_create :upload_image_from_auth
def upload_image_from_auth
auth = self.authentications.first
unless auth.nil?
self.remote_image_url = auth.larger_image
self.save
end
end

How can I restrict access ActiveAdmin login page by ip?

rails version
rails 3.2.1
Goal:
Access ActiveAdmin login page only office computer.
Code:
route.rb
constraints(:ip => /(^127.0.0.1$)|(^192.168.10.[0-9]*$)/) do
match 'admin/' => 'admin#login'
end
It is not work, any suesstion?
==========================
I edit my route.rb follow code
constraints(:ip => /(^127.0.0.1$)|(^192.168.10.[0-9]*$)/) do
ActiveAdmin.routes(self)
end
devise_for :admin_users, ActiveAdmin::Devise.config
it's work!
Refer to Rails guides Chapter routing (http://guides.rubyonrails.org/routing.html#advanced-constraints):
class WhitelistConstraint
  def initialize
    #ips = Whitelist.retrieve_ips
  end
 
  def matches?(request)
    #ips.include?(request.remote_ip)
  end
end
 
TwitterClone::Application.routes.draw do
  match 'admin/' => 'admin#login',
    :constraints => WhitelistConstraint.new
end
I'm sure this can also be done using another way but I'm sure you get the point.
I use this way, because you are able to move some logic out into a class if it is too complex for routes.
This class must have a matches? method defined on it which either returns true if the user should be given access to that route, or false if the user should not.
It helps me to add ips to the array without regex.
I hope, it helps someone)
More info - https://api.rubyonrails.org/v5.2.2/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-constraints
class WhitelistConstraint
IPS = %w[
143.132.200.43,
]
def self.matches?(request)
IPS.include?(request.remote_ip)
end
end
Rails.application.routes.draw do
constraints(WhitelistConstraint) do
ActiveAdmin.routes(self)
mount Sidekiq::Web => '/sidekiq'
end
end

How to use same cached page for different urls in rails?

I have two urls that basically renders the same page. The minor differences can be easily executed via javascript, based on the location.href. Anyway, even when the routes point to the same controller#action, the second route is not using the page cached by the former. How can I achieve this?
I have a interesting requirement in my website opposite to you -- Different pages can be returned from a same url because of different themes. So I came up a solution called "anonymous cache", and I make my own cache key including the extra parameters. But I think this solution can give you some clues.
module AnonymousCache
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def caches_page_for_anonymous(*pages)
before_filter :check_cache_for_anonymous, :only => pages
after_filter :cache_for_anonymous, :only => pages
end
end
def check_cache_for_anonymous
return unless perform_caching
return if logged_in?
path = anon_cache_path
if content = Rails.cache.read(path)
send_data(content,
:type => 'text/html;charset=utf-8', :disposition => 'inline')
return false
end
end
def cache_for_anonymous
return unless perform_caching
return if logged_in?
path = anon_cache_path
#expires_in ||= 1.hour
self.class.benchmark "Cached page for guest: #{path}" do
Rails.cache.write(path, response.body, :expires_in => #expires_in.to_i)
end
end
protected :check_cache_for_anonymous
protected :cache_for_anonymous
private
def anon_cache_path()
path1 = File.join(request.host, current_theme, request.path)
q = request.query_string
path1 = "#{path1}?#{q}" unless q.empty?
path1
end
end
anon_cache_path method is where I make canonical key for the page cache. You can see I includes current_theme in it.
You can copy this and changes anon_cache_path according to your requirements.

Error when saving a Backbone.js model with Rails

I have Backbone.js collection and model for a project object:
window.Project = Backbone.Model.extend();
window.Projects = Backbone.Collection.extend({
model: Project,
url: '/projects'
});
I have setup a rails controller to respond to the Backbone.js collection:
class ProjectsController < ApplicationController
def index
render :json => Project.all
end
def create
project = Project.create! params
render :json => project
end
end
Index works fine and I get a list of projects in my web app. The problem is if I try and create a model on the Projects collection I get a 500 error from the server.
The error message on the server is as follows:
Started POST "/projects" for 127.0.0.1 at 2011-08-21 08:27:56 +0100
Processing by ProjectsController#create as JSON
Parameters: {"title"=>"another test"}
Completed 500 Internal Server Error in 16ms
ActiveRecord::UnknownAttributeError (unknown attribute: action):
app/controllers/projects_controller.rb:8:in `create'
I am not sure what the unknown attribute: action is referring to.
For info I have set up the projects_controller as resources :projects. I have also set rails to ActiveRecord::Base.include_root_in_json = false.
Yes, Rails always adds the action and controller to params. The parameters come from ActionDispatch::Http::Parameters:
def parameters
#env["action_dispatch.request.parameters"] ||= begin
params = request_parameters.merge(query_parameters)
params.merge!(path_parameters)
encode_params(params).with_indifferent_access
end
end
And path_parameters:
Returns a hash with the parameters used to form the path of the request. Returned hash keys are strings:
{'action' => 'my_action', 'controller' => 'my_controller'}
So you shouldn't be doing project = Project.create! params. You could go the update_attributes route:
project = Project.new
project.update_attributes params[:model_name]
But this assumes that you have what you need in a sub-hash of params and it won't call your validators. Backbone won't namespace your attributes by default but you could override Backbone.sync and do it yourself. Still, you probably want your validations so update_attributes should generally be avoided.
Your best bet is to pull exactly the attributes out of params that you're expecting to be there. This is even the Backbone recommended practise:
*(In real code, never use update_attributes blindly, and always whitelist the attributes you allow to be changed.)*
You can enable parameter wrapping. Add a file in the initializer directory with:
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
and, for json request, you post params will now be wrapped with the model name.

How do I write a Rails 3.1 engine controller test in rspec?

I have written a Rails 3.1 engine with the namespace Posts. Hence, my controllers are found in app/controllers/posts/, my models in app/models/posts, etc. I can test the models just fine. The spec for one model looks like...
module Posts
describe Post do
describe 'Associations' do
it ...
end
... and everything works fine.
However, the specs for the controllers do not work. The Rails engine is mounted at /posts, yet the controller is Posts::PostController. Thus, the tests look for the controller route to be posts/posts.
describe "GET index" do
it "assigns all posts as #posts" do
Posts::Post.stub(:all) { [mock_post] }
get :index
assigns(:posts).should eq([mock_post])
end
end
which yields...
1) Posts::PostsController GET index assigns all posts as #posts
Failure/Error: get :index
ActionController::RoutingError:
No route matches {:controller=>"posts/posts"}
# ./spec/controllers/posts/posts_controller_spec.rb:16
I've tried all sorts of tricks in the test app's routes file... :namespace, etc, to no avail.
How do I make this work? It seems like it won't, since the engine puts the controller at /posts, yet the namespacing puts the controller at /posts/posts for the purpose of testing.
I'm assuming you're testing your engine with a dummy rails app, like the one that would be generated by enginex.
Your engine should be mounted in the dummy app:
In spec/dummy/config/routes.rb:
Dummy::Application.routes.draw do
mount Posts::Engine => '/posts-prefix'
end
My second assumption is that your engine is isolated:
In lib/posts.rb:
module Posts
class Engine < Rails::Engine
isolate_namespace Posts
end
end
I don't know if these two assumptions are really required, but that is how my own engine is structured.
The workaround is quite simple, instead of this
get :show, :id => 1
use this
get :show, {:id => 1, :use_route => :posts}
The :posts symbol should be the name of your engine and NOT the path where it is mounted.
This works because the get method parameters are passed straight to ActionDispatch::Routing::RouteSet::Generator#initialize (defined here), which in turn uses #named_route to get the correct route from Rack::Mount::RouteSet#generate (see here and here).
Plunging into the rails internals is fun, but quite time consuming, I would not do this every day ;-) .
HTH
I worked around this issue by overriding the get, post, put, and delete methods that are provided, making it so they always pass use_route as a parameter.
I used Benoit's answer as a basis for this. Thanks buddy!
module ControllerHacks
def get(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "GET")
end
# Executes a request simulating POST HTTP method and set/volley the response
def post(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "POST")
end
# Executes a request simulating PUT HTTP method and set/volley the response
def put(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "PUT")
end
# Executes a request simulating DELETE HTTP method and set/volley the response
def delete(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "DELETE")
end
private
def process_action(action, parameters = nil, session = nil, flash = nil, method = "GET")
parameters ||= {}
process(action, parameters.merge!(:use_route => :my_engine), session, flash, method)
end
end
RSpec.configure do |c|
c.include ControllerHacks, :type => :controller
end
Use the rspec-rails routes directive:
describe MyEngine::WidgetsController do
routes { MyEngine::Engine.routes }
# Specs can use the engine's routes & named URL helpers
# without any other special code.
end
– RSpec Rails 2.14 official docs.
Based on this answer I chose the following solution:
#spec/spec_helper.rb
RSpec.configure do |config|
# other code
config.before(:each) { #routes = UserManager::Engine.routes }
end
The additional benefit is, that you don't need to have the before(:each) block in every controller-spec.
Solution for a problem when you don't have or cannot use isolate_namespace:
module Posts
class Engine < Rails::Engine
end
end
In controller specs, to fix routes:
get :show, {:id => 1, :use_route => :posts_engine}
Rails adds _engine to your app routes if you don't use isolate_namespace.
I'm developing a gem for my company that provides an API for the applications we're running. We're using Rails 3.0.9 still, with latest Rspec-Rails (2.10.1). I was having a similar issue where I had defined routes like so in my Rails engine gem.
match '/companyname/api_name' => 'CompanyName/ApiName/ControllerName#apimethod'
I was getting an error like
ActionController::RoutingError:
No route matches {:controller=>"company_name/api_name/controller_name", :action=>"apimethod"}
It turns out I just needed to redefine my route in underscore case so that RSpec could match it.
match '/companyname/api_name' => 'company_name/api_name/controller_name#apimethod'
I guess Rspec controller tests use a reverse lookup based on underscore case, whereas Rails will setup and interpret the route if you define it in camelcase or underscore case.
It was already mentioned about adding routes { MyEngine::Engine.routes }, although it's possible to specify this for all controller tests:
# spec/support/test_helpers/controller_routes.rb
module TestHelpers
module ControllerRoutes
extend ActiveSupport::Concern
included do
routes { MyEngine::Engine.routes }
end
end
end
and use in rails_helper.rb:
RSpec.configure do |config|
config.include TestHelpers::ControllerRoutes, type: :controller
end