Search Results

Search found 129 results on 6 pages for 'actioncontroller'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • RSpec mocking a nested model in Rails - ActionController problem

    - by emson
    Hi All I am having a problem in RSpec when my mock object is asked for a URL by the ActionController. The URL is a Mock one and not a correct resource URL. I am running RSpec 1.3.0 and Rails 2.3.5 Basically I have two models. Where a subject has many notes. class Subject < ActiveRecord::Base validates_presence_of :title has_many :notes end class Note < ActiveRecord::Base validates_presence_of :title belongs_to :subject end My routes.rb file nests these two resources as such: ActionController::Routing::Routes.draw do |map| map.resources :subjects, :has_many => :notes end The NotesController.rb file looks like this: class NotesController < ApplicationController # POST /notes # POST /notes.xml def create @subject = Subject.find(params[:subject_id]) @note = @subject.notes.create!(params[:note]) respond_to do |format| format.html { redirect_to(@subject) } end end end Finally this is my RSpec spec which should simply post my mocked objects to the NotesController and be executed... which it does: it "should create note and redirect to subject without javascript" do # usual rails controller test setup here subject = mock(Subject) Subject.stub(:find).and_return(subject) notes_proxy = mock('association proxy', { "create!" => Note.new }) subject.stub(:notes).and_return(notes_proxy) post :create, :subject_id => subject, :note => { :title => 'note title', :body => 'note body' } end The problem is that when the RSpec post method is called. The NotesController correctly handles the Mock Subject object, and create! the new Note object. However when the NoteController#Create method tries to redirect_to I get the following error: NoMethodError in 'NotesController should create note and redirect to subject without javascript' undefined method `spec_mocks_mock_url' for #<NotesController:0x1034495b8> Now this is caused by a bit of Rails trickery that passes an ActiveRecord object (@subject, in our case, which isn't ActiveRecord but a Mock object), eventually to url_for who passes all the options to the Rails' Routing, which then determines the URL. My question is how can I mock Subject so that the correct options are passed so that I my test passes. I've tried passing in :controller = 'subjects' options but no joy. Is there some other way of doing this? Thanks...

    Read the article

  • ActionController::MethodNotAllowed

    - by Lowgain
    I have a rails model called 'audioclip'. I orginally created a scaffold with a 'new' action, which I replaced with 'new_record' and 'new_upload', becasue there are two ways to attach audio to this model. Going to /audioclips/new_record doesn't work because it takes 'new_record' as if it was an id. Instead of changing this, I was trying to just create '/record_clip' and '/upload_clip' paths. So in my routes.db I have: map.record_clip '/record_clip', :controller => 'audioclips', :action => 'new_record' map.upload_clip '/upload_clip', :controller => 'audioclips', :action => 'new_upload' When I navigate to /record_clip, I get ActionController::MethodNotAllowed Only get, head, post, put, and delete requests are allowed. I'm not extremely familiar with the inner-workings of routing yet. What is the problem here? (If it helps, I have these two statements above map.resources = :audioclips

    Read the article

  • ActionController::RoutingError (No route matches {:action=>"show", :controller=>"users", :id=>nil}):

    - by Matt Bishop
    I have been trying to fix this routing error for a long time. I would appreciate any assistance! This error is preventing me from being able to authenticate. Here is what I am getting in my Heroku logs. app/controllers/authentications_controller.rb:12:in `create' ActionController::RoutingError (No route matches {:action=>"show", :controller=>"users", :id=>nil}) Here is the routes.rb file: Company::Application.routes.draw do resources :profile_individual resources :careers match 'careers' => 'careers#index' match 'about' => 'about#index' constraints(:subdomain => /^$|www/) do devise_for :users resources :authentications, :identities #, :beta_invitations resources :users do resources :invitations, :controller => 'UserInvitation' do post :upload, :on => :collection get :email_template, :on => :collection get :plaintext_template, :on => :collection get :facebook_invitation, :on => :collection end member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns end end resources :password_resets do get 'password_reset' => 'password_resets#show', :as => 'password_reset' end resources :events, :only => [:new, :index, :create] resources :organizations, :only => [:index, :create] resources :orders do post :ipn, :on => :member resource :payment do member do post :relay_response get :receipt end end resource :paypal_integration do member do get :authorize get :cancel post :finalize end end end match '/users/:id/impact/money/:d' => 'users#impact_money_graph', :constraints => {:d => /\d+{4}_\d+{2}-\d+{2}/}, :as => :user_impact_money match '/users/:id/impact/money' => 'users#impact_money_graph', :as => :user_impact_money match '/users/:id/impact/recruits/:d' => 'users#impact_recruits_graph', :constraints => {:d => /\d+{4}_\d+{2}-\d+{2}/}, :as => :user_impact_recruits match '/users/:id/impact/recruits' => 'users#impact_recruits_graph', :as => :user_impact_recruits match '/auth/failure' => 'authentications#failure' match '/auth/:provider/callback' => 'authentications#create' match '/auth/:provider/callback' => 'authentications#show', :controller => 'users', :as => :login match '/logout' => 'authentications#destroy', :as => :logout match '/login' => 'authentications#new', :as => :login match "/join_team/:id" => "team_members#join", :as => :join_team match "/rsvp/:id" => "rsvps#show", :as => :rsvp match "/signup" => 'authentications#signup', :as => :signup match "/beacon/:id.gif" => "email_beacons#show", :as => :email_beacon root :to => "homes#show" match '/corporate_giving' => "homes#corporate_giving" end constraints(Subdomain) do resource :organization, :path => "/", :only => [:edit, :update] do member do get :org_photos_videos get :org_recent_activity end end resources :events, :except => [:index] do post :publish, :on => :member resource :supporter_invite resource :team_management do post :mailer, :on => :member end resource :team_member do post :invite, :on => :member end resource :rsvp do put :make_order, :on => :collection get :make_order, :on => :collection end resources :invites do post :upload, :on => :collection end resources :ticket_tiers, :team_members end match "/events" => redirect("/") root :to => "organizations#show" end namespace :admin do resources :stats resources :organizations resources :campaigns do resources :rewards resources :contents put :header, :action => 'header_update' end resources :users do member do post :grant_access post :revoke_access end end resources :nonprofits do member do put :approve put :revoke end end end resources :campaigns do get :find_charities, :on => :collection get :how_many_charities, :on => :collection member do post :join get :join post :header, :action => 'header_creation' put :header, :action => 'header_update' end resources :rewards resources :contents resource :donations do resource :paypal_integration, :controller => 'donations' do member do get :authorize get :cancel post :finalize end end end end match '/campaigns/:id/graph/:d' => 'campaigns#graph', :constraints => {:d => /\d+{4}_\d+ {2}-\d+{2}/}, :as => :graph_campaign match '/campaigns/:id/graph' => 'campaigns#graph', :as => :graph_campaign resources :business_campaigns, :controller => 'campaigns' resources :businesses do put :logo, :on => :collection, :action => 'upload_logo' member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns end end resources :nonprofit_campaigns, :controller => 'campaigns' resources :nonprofits do put :logo, :on => :collection, :action => 'upload_logo' member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns get :supporting_campaigns end end resources :publicities match '/campaigns/:campaign_id/rewards/:id' => 'campaigns#reward', :via => :get match "/robots.txt" => "application#robots_txt" match "/beta_invitations" => redirect('/') resource :sitemap resources :referrals end Here is my authentications_controller.rb file class AuthenticationsController < ApplicationController skip_before_filter :require_beta_access before_filter :redirect_to_profile_if_logged_in, :only => [:create, :new] layout :resolve_layout def create omniauth = request.env["omniauth.auth"] authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) if authentication && authentication.user.present? sign_in(:user, authentication.user) redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) elsif current_user current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid']) redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) else user = User.new user.apply_omniauth(omniauth) logger.debug "=======================auth=============================" logger.debug session[:referrer_token] logger.debug "========================================================" if session[:referrer_token] publicity = Publicity.find_by_token(session[:referrer_token]) user.invited_by = publicity user.recruited_by = publicity end if user.save sign_in(user) unless session[:redirect_to] session[:referrer_token] = nil end redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) #redirect_to session[:redirect_to] || campaigns_url(:tc => request.env['omniauth.params']['tc']) #tc is for AB testing else session[:omniauth] = omniauth.except('extra') redirect_to signup_path end end end def failure flash[:error] = "Please check your email and password and try again" redirect_to login_path end def destroy reset_session redirect_to root_path end def signup # end private def redirect_to_profile_if_logged_in redirect_to user_path(current_user.permalink) if current_user end def resolve_layout case action_name when "new", "signup" "authentication" else "selfcontained" end end end I am adding my appplication_controller.rb too: class ApplicationController < ActionController::Base #Wrote by George for beta users -before_filter :require_beta_access before_filter :save_referrer_token protect_from_forgery helper_method :organization_admin?, :team_member?, :profile_url, :current_profile def set_headers # Set our headers here end def save_referrer_token #session.delete(:referrer_token) if params[:ref] publicity = Publicity.find_by_token(params[:ref]) logger.debug "========================================================" logger.debug current_profile.nil? logger.debug publicity.creator logger.debug current_profile logger.debug current_profile != publicity.creator session[:referrer_token] = params[:ref] if current_profile.nil? or publicity.creator != current_profile logger.debug session[:referrer_token] logger.debug "========================================================" end end def robots_txt robots = File.read(Rails.root + "public/robots.#{Rails.env}.txt") render :text => robots, :layout => false, :content_type => "text/plain" end def load_organization @organization = Organization.find_by_permalink(request.subdomain) raise ActiveRecord::RecordNotFound if @organization.nil? end def require_user unless current_user session[:redirect_to] = request.url redirect_to login_url(:host => request.domain) end end def require_beta_access if !current_user redirect_to root_url(:host => request.domain) elsif !current_user.beta_access? redirect_to new_beta_invitation_url(:host => request.domain) end end def require_organization_admin unless organization_admin? redirect_to root_url(:subdomain => @organization.permalink) end end def team_member? if current_user && @event.team_memberships.where(:user_id => current_user.id).count != 0 true end end def organization_admin? if current_user && current_user.beta_access? && @organization && @organization.memberships.where(:user_id => current_user.id, :role => 'admin').count != 0 true end end def profile_url(profile, opt = nil) if profile == current_user user_url(profile, :host => opt[:host]) elsif profile.is_a? BusinessProfile business_url(profile) elsif profile.is_a? NonprofitProfile nonprofit_url(profile) end end def set_current_profile(profile) session[:current_profile] = profile end def current_user @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] end def current_profile #if session session[:current_profile] || current_user #else # nil #end end IGIVEMORE_HTML5_OPTIOINS = { :style => 'z-index: 0;',:width => '290', :height => '200', :frameborder => '0', :url_params => {:wmode=>"opaque"} } def campaign_header_body(camp, opt = IGIVEMORE_HTML5_OPTIOINS) if camp.header_type == Campaign::HEADER_YOUTUBE youtube_html5(camp.header_url, opt).html_safe elsif camp.header_type == Campaign::HEADER_IMAGE "<img src=\"#{camp.header_url}\" width=\"#{opt[:width]}\" height=\"#{opt[:height]}\"/>'".html_safe else "Unsupported Type!!" end end def youtube_html5(url, opt) begin video = YouTubeIt::Client.new.video_by(url) video.embed_html5(opt).gsub(/http:\/\//,"https://") rescue => e "<div style='color:red; width:290px; height:100px; padding-top:100px'>Given Video URL has problem.</div>" end end end

    Read the article

  • ActionController::RoutingError

    - by Steve
    Hi All, I am just learning Rails. I had encountered a routing error, though I think I have specified the correct rules in the routing.rb. I have attached the code. Please help routing.rb map.connect ':controller/:action' map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' Controller class EntriesController < ApplicationController def sign_in @name = params[:visitor_name] end end View <html> <head><title>Hello <%=h @name %></title></head> <body> <%=h @name %> <% form_tag :action => 'sign_in' do %> <p>Enter your name: <%= text_field_tag 'visitor_name', @name %></p> <%= submit_tag 'Sign in' %> <% end %> </body> </html> Thanks

    Read the article

  • Rails equivalent of respond_to |format| with a straight render

    - by brad
    I'm working with ActiveResource a lot so my service models are only using XML. Thus, I have no need for a respond_to block, I literally just render :xml => @model I can't however figure out how to render a 404 header using this. I've had to resort to respond_to, which I think adds a few unnecessary method calls. Here's what I'm using: respond_to do |format| if (record_found) render :xml => @some_record else format.xml{ head :not_found } end end but I just want something like render :xml => head :not_found which doesn't work. Can anyone tell me the proper syntax?

    Read the article

  • Rails before_filter on subclasses beeing called twice

    - by rubenfonseca
    Hi! I'm at Rails 2.3.5 and I have this problem: class BaseController < ApplicationController before_filter :foo, :only => [:index] end class ChildController < BaseController before_filter :foo, :only => [:index, :show, :other, :actions] end The problem is that on ChildController, the :foo before filter gets called twice. I've tried a number of workarounds around this problem. If I don't include the :index action on the child, it never gets called for that action. The solution I found works, but is very very ugly skip_before_filter :foo before_filter :foo, :only => [:index, :show, :other, :actions] Is there a better way to solve this problem? Thanks

    Read the article

  • How to make ActionController::Base.asset_host and Base.relative_url_root independent?

    - by GSP
    In our Intranet environment we have a decree that common assets (stylesheets, images, etc) should be fed from Apache root while Rails apps runs from from a "sub directory" (a proxy to a Mongrel cluster). In other words: <%= stylesheet_tag '/common' %> # <link href="http://1.1.1.1/stylesheets/common.css" /> <%= link_to 'Home', :controller=>'home', :action=>'index' %> # <a href="http://1.1.1.1/myapp/" /> What I would like to do is define the assets and relative url in my configuration like this: ActionController::Base.asset_host=http://1.1.1.1 ActionController::Base.relative_url_root=/myapp But when I do this, the relative_url_root value gets appended to the asset_host value. (e.g. <link href="http://1.1.1.1/myapp/stylesheets/common.css"> ) Is there a way to stop this? And, more importantly, is there a best practice for how to deploy a rails app to an environment like this? (BTW, I don't want to simply hard code my asset paths since the development environment does not match the test and production environments.) Environment: Rails 2.3.4 Ruby 1.8.7 RedHat Linux 5.4?

    Read the article

  • ActionController::InvalidAuthenticityToken: verified with authentication token on the form!

    - by goodwill
    I don't know why it happens but my form for some reason does not post properly. I am very sure the form contains the required authentication token: <form action="/account/complete_verify_email/4df78710-e27b-4527-bd2d-71cd2e9a1271" method="post"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="341b07dfa682ed11a045e19956e2e3f5f499e8cb"></div> <input id="password" name="password" type="password"> <input name="commit" type="submit" value="Continue"> </form> Note the authenticity_token is there. What happened? And YOU KNOW WHAT? Quitting Safari and restart again solved the issue... but I can't think of what kind of intermittent behaviour could cause such problem.

    Read the article

  • JSF 2.1 Spring 3.0 Integration

    - by danny.lesnik
    I'm trying to make very simple Spring 3 + JSF2.1 integration according to examples I googled in the web. So here is my code: My HTML submitted to actionController.actionSubmitted() method: <h:form> <h:message for="textPanel" style="color:red;" /> <h:panelGrid columns="3" rows="5" id="textPanel"> //all my bean prperties mapped to HTML code. </h:panelGrid> <h:commandButton value="Submit" action="#{actionController.actionSubmitted}" /> </h:form> now the Action Controller itself: @ManagedBean(name="actionController") @SessionScoped public class ActionController implements Serializable{ @ManagedProperty(value="#{user}") User user; @ManagedProperty(value="#{mailService}") MailService mailService; public void setMailService(MailService mailService) { this.mailService = mailService; } public void setUser(User user) { this.user = user; } private static final long serialVersionUID = 1L; public ActionController() {} public String actionSubmitted(){ System.out.println(user.getEmail()); mailService.sendUserMail(user); return "success"; } } Now my bean Spring: public interface MailService { void sendUserMail(User user); } public class MailServiceImpl implements MailService{ @Override public void sendUserMail(User user) { System.out.println("Mail to "+user.getEmail()+" sent." ); } } This is my web.xml <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <!-- Welcome page --> <welcome-file-list> <welcome-file>index.xhtml</welcome-file> </welcome-file-list> <!-- JSF mapping --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> my applicationContext.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="mailService" class="com.vanilla.jsf.services.MailServiceImpl"> </bean> </beans> my faces-config.xml is the following: <application> <el-resolver> org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> <message-bundle> com.vanilla.jsf.validators.MyMessages </message-bundle> </application> <managed-bean> <managed-bean-name>actionController</managed-bean-name> <managed-bean-class>com.vanilla.jsf.controllers.ActionController</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>mailService</property-name> <value>#{mailService}</value> </managed-property> </managed-bean> <navigation-rule> <from-view-id>index.xhtml</from-view-id> <navigation-case> <from-action>#{actionController.actionSubmitted}</from-action> <from-outcome>success</from-outcome> <to-view-id>submitted.xhtml</to-view-id> <redirect /> </navigation-case> </navigation-rule> My Problem is that I'm getting NullPointerExeption because my mailService Spring bean is null. public String actionSubmitted(){ System.out.println(user.getEmail()); //mailService is null Getting NullPointerException mailService.sendUserMail(user); return "success"; }

    Read the article

  • Rails.cache throws "marshal dump" error when changed from memory store to memcached store

    - by gsmendoza
    If I set this in my environment config.action_controller.cache_store = :mem_cache_store ActionController::Base.cache_store will use a memcached store but Rails.cache will use a memory store instead: $ ./script/console >> ActionController::Base.cache_store => #<ActiveSupport::Cache::MemCacheStore:0xb6eb4bbc @data=<MemCache: 1 servers, ns: nil, ro: false>> >> Rails.cache => #<ActiveSupport::Cache::MemoryStore:0xb78b5e54 @data={}> In my app, I use Rails.cache.fetch(key){ object } to cache objects inside my helpers. All this time, I assumed that Rails.cache uses the memcached store so I'm surprised that it uses memory store. If I change the cache_store setting in my environment to config.cache_store = :mem_cache_store both ActionController::Base.cache_store and Rails.cache will now use the same memory store, which is what I expect: $ ./script/console >> ActionController::Base.cache_store => #<ActiveSupport::Cache::MemCacheStore:0xb7b8e928 @data=<MemCache: 1 servers, ns: nil, ro: false>, @middleware=#<Class:0xb7b73d44>, @thread_local_key=:active_support_cache_mem_cache_store_local_cache> >> Rails.cache => #<ActiveSupport::Cache::MemCacheStore:0xb7b8e928 @data=<MemCache: 1 servers, ns: nil, ro: false>, @middleware=#<Class:0xb7b73d44>, @thread_local_key=:active_support_cache_mem_cache_store_local_cache> However, when I run the app, I get a "marshal dump" error in the line where I call Rails.cache.fetch(key){ object } no marshal_dump is defined for class Proc Extracted source (around line #1): 1: Rails.cache.fetch(fragment_cache_key(...), :expires_in => 15.minutes) { ... } vendor/gems/memcache-client-1.8.1/lib/memcache.rb:359:in 'dump' vendor/gems/memcache-client-1.8.1/lib/memcache.rb:359:in 'set_without_newrelic_trace' What gives? Is Rails.cache meant to be a memory store? Should I call controller.cache_store.fetch in the places where I call Rails.cache.fetch?

    Read the article

  • Rails - difference between config.cache_store and config.action_controller.cache_store?

    - by gsmendoza
    If I set this in my environment config.action_controller.cache_store = :mem_cache_store ActionController::Base.cache_store will use a memcached store but Rails.cache will use a memory store instead: $ ./script/console >> ActionController::Base.cache_store => #<ActiveSupport::Cache::MemCacheStore:0xb6eb4bbc @data=<MemCache: 1 servers, ns: nil, ro: false>> >> Rails.cache => #<ActiveSupport::Cache::MemoryStore:0xb78b5e54 @data={}> In my app, I use Rails.cache.fetch(key){ object } to cache objects inside my helpers. All this time, I assumed that Rails.cache uses the memcached store so I'm surprised that it uses memory store. If I change the cache_store setting in my environment to config.cache_store = :mem_cache_store both ActionController::Base.cache_store and Rails.cache will now use the same memory store, which is what I expect: $ ./script/console >> ActionController::Base.cache_store => #<ActiveSupport::Cache::MemCacheStore:0xb7b8e928 @data=<MemCache: 1 servers, ns: nil, ro: false>, @middleware=#<Class:0xb7b73d44>, @thread_local_key=:active_support_cache_mem_cache_store_local_cache> >> Rails.cache => #<ActiveSupport::Cache::MemCacheStore:0xb7b8e928 @data=<MemCache: 1 servers, ns: nil, ro: false>, @middleware=#<Class:0xb7b73d44>, @thread_local_key=:active_support_cache_mem_cache_store_local_cache> However, when I run the app, I get a "marshal dump" error in the line where I call Rails.cache.fetch(key){ object } no marshal_dump is defined for class Proc Extracted source (around line #1): 1: Rails.cache.fetch(fragment_cache_key(...), :expires_in => 15.minutes) { ... } vendor/gems/memcache-client-1.8.1/lib/memcache.rb:359:in 'dump' vendor/gems/memcache-client-1.8.1/lib/memcache.rb:359:in 'set_without_newrelic_trace' What gives? Is Rails.cache meant to be a memory store? Should I call controller.cache_store.fetch in the places where I call Rails.cache.fetch?

    Read the article

  • Rails 3 Flash Uploader

    - by klynch
    I am trying to get Uploadify working with Rails 3. However, I can't insert the middleware with the correct arguments. This is the Rails 2 way: ActionController::Dispatcher.middleware.insert_before( ActionController::Session::CookieStore, FlashSessionCookieMiddleware, ActionController::Base.session_options[:key] ) This is what I have so far for Rails 3: Rails.application.config.middleware.insert_before( Rails.application.config.session_store, FlashSessionCookieMiddleware, Rails.application.config.session_options[:key] ) However, this gives: kevin$hephaestus:$exposure [1035 | 0]% rake middleware (in /Users/kevin/Projects/exposure) rake aborted! protected method `session_options' called for #<Rails::Application::Configuration:0x101eb28d0> (See full trace by running task with --trace) zsh: exit 1 rake middleware When I comment out the session_options argument, the middleware is successfully inserted, but it can't do what it is supposed to. Any suggestions?

    Read the article

  • Rails - How do you dynamically call the request methods "get put destroy etc" at runtime in tests

    - by adam
    I'm always writing tests to check my controller restricts people from certain actions depending on their status i.e. logged in, admin? etc Regardless of whether its a get to :index or a puts to :create the code is always the same. I'm trying to refactor this so that i have one method such as should_redirect_unauthenticated_to_login_action(request, action) and call it like so should_redirect_unauthenticated_to_login_action(:get, :index) = get :index But not sure how to dynamically call the various response methods rails provides for functional tests which seem to live in the module ActionController I mucked around with module = Kernel.const_get("ActionController") module::TestProcess.get NoMethodError: undefined method `get' for ActionController::TestProcess:Module can anyone help (im very new to dynamic calling in ruby)

    Read the article

  • How properly perform passing operation result to View

    - by atomAltera
    I'm developing web site on self made MVC engine. I have actionController that handles operations like register, login, post submit and etc. actionController receives operation name and parameters. Of course it mast handle errors such user with same nick already exists or password is to short about which action handler have to notify user. The question is which is the best way to organize errors, such that View could easily get localized user notification message. I see two ways First one: define error constants like ERR_NICK_BUSY = '1' ERR_NICK_INVALID = '2' ... and localization map local[ERR_NICK_BUSY] = 'User with the same nick already registered' local[ERR_NICK_INVALID ] = 'Nick, you entered is invalid' ... And second one: define abstract constants like ERR_FIELD_BUSY = '1' ERR_FIELD_INVALID = '2' ... and pass them with field name. In this case localization looks like local['nick_'+ERR_FIELD_BUSY] = 'User with the same nick already registered' ... I don't like both this methods. Can you advise something else?

    Read the article

  • Path parsing in rails

    - by fl00r
    Hi! I am looking for method for parsing route path like this: ActionController::Routing.new("post_path").parse #=> {:controller => "posts", :action => "index"} It should be opposite to url_for Upd I've found out: http://stackoverflow.com/questions/2222522/what-is-the-opposite-of-url-for-in-rails-a-function-that-takes-a-path-and-genera ActionController::Routing::Routes.recognize_path("/posts") So now I need to convert posts_path into "/posts"

    Read the article

  • Rails: url_for to be available in a isolated class that must be instanced

    - by Totty
    Rails: url_for to be available in a isolated class that must be instanced: class ProfilePresenter < ActionController::Base attr_reader :profile def initialize(profile) super @a = url_for(:controller => 'profiles', :action => 'view', :profile_url => 'dd') @a @profile = profile end end How to make the url_for work? i tried to extend the ActionController::Base and the ActionView::Base and i cant :s

    Read the article

  • rspec and ruby 1.9.1: problem with dummy controller and routes

    - by giorgian
    I want to test a module that basically executes some verify statements, to ensure that actions are invoked with the correct method. # /lib/rest_verification.rb module RestVerification def self.included(base) # :nodoc: base.extend(ClassMethods) end module ClassMethods def verify_rest_actions verify :method => :post, :only => [:create], :redirect_to => { :action => :new } ... end end end I tried this: describe RestVerification do class FooController < ActionController::Base include RestVerification verify_rest_actions def new ; end def index ; end def create ; end def edit ; end def update ; end def destroy ; end end # controller_name 'foo' # this only works with ruby 1.8.7 : 1.9.1 says "uninitialized constant FooController" tests FooController # this works with both before(:each) do ActionController::Routing::Routes.draw do |map| map.resources :foo end end after(:each) do ActionController::Routing::Routes.reload! end it ':create should redirect to :new if invoked with wrong verb' do [:get, :put, :delete].each do |verb| send verb, :create response.should redirect_to(new_foo_url) end end ... end When testing: $ ruby -v ruby 1.8.7 (2010-01-10 patchlevel 249) [i486-linux] $ rake RestVerification :create should redirect to :new if invoked with wrong verb Finished in 0.175586 seconds $ rvm use 1.9.1 Using ruby 1.9.1 p378 $ rake RestVerification :create should redirect to :new if invoked with wrong verb (FAILED - 1) 1) 'RestVerification :create should redirect to :new if invoked with wrong verb' FAILED expected redirect to "http://test.host/foo/new", got redirect to "http://test.host/spec/rails/example/controller_example_group/subclass_1/foo/new" Is this a known issue? Is there a workaround?

    Read the article

  • Rails choking on the content of this request because of protect_from_forgery

    - by randombits
    I'm trying to simply test my RESTful API with cURL. Using the following invocation: curl -d "name=jimmy" -H "Content-Type: application/x-www-form-urlencoded" http://127.0.0.1:3000/people.xml -i Rails is dying though: ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): :8:in `synchronize' Looks like it's running this through a protect_from_forgery filter. I thought protect_from_forgery is excluded for non-HTML HTTP POST/PUT/DELETE type requests? This is clearly targeting the XML format. If I pass actual XML content, it works. But my users will be submitting POST data as URL encoded parameters. I know all the various ways I can disable protect_from_forgery but what's the proper way of handling this? I want to leave it on so that when I do have HTML based forms and handle format.html, I don't forget to re-enable it for then. I want users to be able to make HTTP POST requests to my XML-based API though and not get bombarded with this.

    Read the article

  • Rails - Multiple top level domains and a single session/cookie

    - by Thadius B
    Hello all, I've been struggling with this for quite awhile and haven't been able to find a solution. I need a user to be able to view multiple top level domains with a single login. My understanding is that this needs to be set in environment.rb and called with before_dispatch. This is what I've come up with: require 'activesupport' require 'dispatcher' module ActionController class Dispatcher def set_session_domain ActionController::Base.session_options.update :session_domain => "#{@request.host}" end before_dispatch :set_session_domain end end However, this does not seem to be working when I try and pull the values from session[:session_domain]. Any help is greatly appreciated.

    Read the article

1 2 3 4 5 6  | Next Page >