Search Results

Search found 10455 results on 419 pages for 'ruby on rails 3 2'.

Page 165/419 | < Previous Page | 161 162 163 164 165 166 167 168 169 170 171 172  | Next Page >

  • Regexs in Ruby getting filename

    - by user1290757
    i am extracting file names of html files using line: filename = File.basename(input_filename, ".*") which currently prints full file name excluding .html extension All files are stored in the form of http^x.x.edu^1^2 all file names begin with http^ and contain edu^ what i want is to extract 2 (which changes) but it is always the second element after .edu I have attempted destructive gsub! but i m weak with regular expressions.

    Read the article

  • How to refactor this Ruby on Rails code?

    - by yuval
    I want to fetch posts based on their status, so I have this code inside my PostsController index action. It seems to be cluttering the index action, though, and I'm not sure it belongs here. How could I make it more concise and where would I move it in my application so it doesn't clutter up my index action (if that is the correct thing to do)? if params[:status].empty? status = 'active' else status = ['active', 'deleted', 'commented'].include?(params[:status]) ? params[:status] : 'active' end case status when 'active' #active posts are not marked as deleted and have no comments is_deleted = false comments_count_sign = "=" when 'deleted' #deleted posts are marked as deleted and have no comments is_deleted = true comments_count_sign = "=" when 'commented' #commented posts are not marked as deleted and do have comments is_deleted = false comments_count_sign = ">" end @posts = Post.find(:all, :conditions => ["is_deleted = ? and comments_count_sign #{comments_count_sign} 0", is_deleted])

    Read the article

  • Best way to associate data files with particular tests in RSpec / Ruby

    - by Bill T
    For my RSpec tests I would to automatically associate data files with each test. To clarify, if my tests each require an xml file as input data and then some xpath statements to validate the responses they get back I would like to externalize the xml and xpath as files and have the testing framework easily associate them with the particular test being run by using the unique ID of the test as the file(s) name. I tried to get this behavior but the solution isn't very clean. I wrote a helper method that takes the value of "description" and combines it with FILE to create a unique identifier which is set into a global variable that other utilities can access. The unique identifier is used to associate the data files I need. I have to call this helper method as the first line of every test, which is ugly. If I have an RSpec example that looks like this: describe "Basic functions of this server I'm testing" do it "should give me back a response" do # Sets a global var to: "my_tests_spec.rb_should_give_me_back_a_response" TestHelper::who_am_i __FILE__, description ... end end Is there some better/cleaner/slicker way I can get an unique ID for each test that I could use to associate data files with? Perhaps something build into RSpec I'm unaware of? Thank you, -Bill

    Read the article

  • Ruby execute code in class getting inherited to

    - by AdamB
    I'm trying to be able to have a global exception capture where I can add extra information when an error happens. I have two classes, "crawler" and "amazon". What I want to do is be able to call "crawl", execute a function in amazon, and use the exception handling in the crawl function. Here are the two classes I have: require 'mechanize' class Crawler Mechanize.html_parser = Nokogiri::HTML def initialize @agent = Mechanize.new end def crawl puts "crawling" begin #execute code in Amazon class here? rescue Exception => e puts "Exception: #{e.message}" puts "On url: #{@current_url}" puts e.backtrace end end def get(url) @current_url = url @agent.get(url) end end class Amazon < Crawler #some code with errors def stuff page = get("http://www.amazon.com") puts page.parser.xpath("//asldkfjasdlkj").first['href'] end end a = Amazon.new a.crawl Is there a way I can call "stuff" inside of "crawl" so I can use that exception handling over the entire stuff function? Is there a better way to accomplish this?

    Read the article

  • Simulating a missing gem in Ruby unit tests

    - by ktex
    Is there any way to simulate the absence of a gem for certain unit tests, short of actually uninstalling and then reinstalling the gem during testing? I am writing a command line utility, and want to make sure that my tests cover cases where a user may not have all of the gems that I support. For instance, I am using fsevents — a Leopard-specific package for monitoring filesystem events — that will never be present on other systems, as well as a growl gem that's purely optional.

    Read the article

  • Ruby Module Inclusion in Methods

    - by Federico Builes
    In class Foo I'd like to include method Bar under certain conditions: module Bar def some_method "orly" end end class Foo def initialize(some_condition) if !some_condition "bar" else class << self; include Bar; end end end end Is there any cleaner (and clearer) way to achieve the include in the method without having to do it inside the singleton class?

    Read the article

  • Beginner += in Ruby

    - by WANNABE
    Looking at this block, I can follow the whole program until I hit, sum += square. What is he point of this line, what does it say??? sum = 0 [1, 2, 3, 4].each do |value| square = value * value sum += square end puts sum

    Read the article

  • Ruby on Rails: restrict file type with Paperclip using a flash uploader

    - by aperture
    I have a pretty basic Paperclip Upload model that is attached to a User model through has_many, and am using Uploadify to do the actual uploading. Flash sends all files with the content type of "application/octet-stream" so using validates_attachment_content_type rejects all files. In my create action, I am able to get the mime-type from the original file name, but only after it's been saved, with: def coerce(params) h = Hash.new h[:upload] = Hash.new h[:upload][:attachment].content_type = MIME::Types.type_for(h[:upload][:attachment].original_filename).to_s ... end and def create diff_params = coerce(params) @upload = Upload.new(diff_params[:upload]) ... end What would be the best way of white listing file types? I am thinking a before_validation method, but I'm not sure how that would work. Any ideas would be welcome.

    Read the article

  • ruby on rails has_many through relationship

    - by BennyB
    Hi i'm having a little trouble with a has_many through relationship for my app and was hoping to find some help. So i've got Users & Lectures. Lectures are created by one user but then other users can then "join" the Lectures that have been created. Users have their own profile feed of the Lectures they have created & also have a feed of Lectures friends have created. This question however is not about creating a lecture but rather "Joining" a lecture that has been created already. I've created a "lecturerelationships" model & controller to handle this relationship between Lectures & the Users who have Joined (which i call "actives"). Users also then MUST "Exit" the Lecture (either by clicking "Exit" or navigating to one of the header navigation links). I'm grateful if anyone can work through some of this with me... I've got: Users.rb model Lectures.rb model Users_controller Lectures_controller then the following model lecturerelationship.rb class lecturerelationship < ActiveRecord::Base attr_accessible :active_id, :joinedlecture_id belongs_to :active, :class_name => "User" belongs_to :joinedlecture, :class_name => "Lecture" validates :active_id, :presence => true validates :joinedlecture_id, :presence => true end lecturerelationships_controller.rb class LecturerelationshipsController < ApplicationController before_filter :signed_in_user def create @lecture = Lecture.find(params[:lecturerelationship][:joinedlecture_id]) current_user.join!(@lecture) redirect_to @lecture end def destroy @lecture = Lecturerelationship.find(params[:id]).joinedlecture current_user.exit!(@user) redirect_to @user end end Lectures that have been created (by friends) show up on a users feed in the following file _activity_item.html.erb <li id="<%= activity_item.id %>"> <%= link_to gravatar_for(activity_item.user, :size => 200), activity_item.user %><br clear="all"> <%= render :partial => 'shared/join', :locals => {:activity_item => activity_item} %> <span class="title"><%= link_to activity_item.title, lecture_url(activity_item) %></span><br clear="all"> <span class="user"> Joined by <%= link_to activity_item.user.name, activity_item.user %> </span><br clear="all"> <span class="timestamp"> <%= time_ago_in_words(activity_item.created_at) %> ago. </span> <% if current_user?(activity_item.user) %> <%= link_to "delete", activity_item, :method => :delete, :confirm => "Are you sure?", :title => activity_item.content %> <% end %> </li> Then you see I link to the the 'shared/join' partial above which can be seen in the file below _join.html.erb <%= form_for(current_user.lecturerelationships.build(:joinedlecture_id => activity_item.id)) do |f| %> <div> <%= f.hidden_field :joinedlecture_id %> </div> <%= f.submit "Join", :class => "btn btn-large btn-info" %> <% end %> Some more files that might be needed: config/routes.rb SampleApp::Application.routes.draw do resources :users do member do get :following, :followers, :joined_lectures end end resources :sessions, :only => [:new, :create, :destroy] resources :lectures, :only => [:create, :destroy, :show] resources :relationships, :only => [:create, :destroy] #for users following each other resources :lecturerelationships, :only => [:create, :destroy] #users joining existing lectures So what happens is the lecture comes in my activity_feed with a Join button option at the bottom...which should create a lecturerelationship of an "active" & "joinedlecture" (which obviously are supposed to be coming from the user & lecture classes. But the error i get when i click the join button is as follows: ActiveRecord::StatementInvalid in LecturerelationshipsController#create SQLite3::ConstraintException: constraint failed: INSERT INTO "lecturerelationships" ("active_id", "created_at", "joinedlecture_id", "updated_at") VALUES (?, ?, ?, ?) Also i've included my user model (seems the error is referring to it) user.rb class User < ActiveRecord::Base attr_accessible :email, :name, :password, :password_confirmation has_secure_password has_many :lectures, :dependent => :destroy has_many :lecturerelationships, :foreign_key => "active_id", :dependent => :destroy has_many :joined_lectures, :through => :lecturerelationships, :source => :joinedlecture before_save { |user| user.email = email.downcase } before_save :create_remember_token validates :name, :presence => true, :length => { :maximum => 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, :presence => true, :format => { :with => VALID_EMAIL_REGEX }, :uniqueness => { :case_sensitive => false } validates :password, :presence => true, :length => { :minimum => 6 } validates :password_confirmation, :presence => true def activity # This feed is for "My Activity" - basically lectures i've started Lecture.where("user_id = ?", id) end def friendactivity Lecture.from_users_followed_by(self) end # lECTURE TO USER (JOINING) RELATIONSHIPS def joined?(selected_lecture) lecturerelationships.find_by_joinedlecture_id(selected_lecture.id) end def join!(selected_lecture) lecturerelationships.create!(:joinedlecture_id => selected_lecture.id) end def exit!(selected_lecture) lecturerelationships.find_by_joinedlecture_id(selected_lecture.id).destroy end end Thanks for any and all help - i'll be on here for a while so as mentioned i'd GREATLY appreciate someone who may have the time to work through my issues with me...

    Read the article

  • Ruby on Rails unknown attribute form error

    - by Ulkmun
    I'm attempting to create a form which will allow me to upload a file.. I've got the following form.. <div class="field"> <%= f.label :title %><br /> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body, "cols" => 100, "rows" => 40 %> </div> <div class="field"> <%= f.label :upload %><br /> <%= f.file_field :upload %> </div> <div class="actions"> <%= f.submit %> </div> I've got a controller which seems to error in this function.. # POST /posts # POST /posts.xml def create @post = Post.new(params[:post]) @post = DataFile.save(params[:upload]) ##render :text => "File has been uploaded successfully" respond_to do |format| if @post.save format.html { redirect_to(@post, :notice => 'Post was successfully created.') } format.xml { render :xml => @post, :status => :created, :location => @post } else format.html { render :action => "new" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end That's the method that get's called when I create the post. The error is unknown attribute: upload app/controllers/posts_controller.rb:42:in ``new' app/controllers/posts_controller.rb:42:in ``create'

    Read the article

  • Ruby and jQuery -- $(document).ajaxSend() not modifying the params as expected

    - by Jason
    I cannot get jquery's ajaxSend (http://api.jquery.com/ajaxSend/) to properly modify the parameters. I have: $(document).ajaxSend(function(event, request, settings) { settings.data = $.deparam(settings.data); settings.data['random'] = new Date().getTime(); settings.data['_method'] = 'get'; settings.data = $.param(settings.data) $.log(settings); }); $(document).ready(function() { //...snip... $.ajaxSetup({ data : { remote : 1, authenticity_token : encodeURIComponent(AUTH_TOKEN) } }); }); The idea here is that we always want 4 param sent across: remote and auth_token always get set properly. However, random and _method (both needed for IE issues) do not get set. Logging settings inside ajaxSend shows me that they are set to settings.data: "remote=1&authenticity_token=6GA9R_snip_253D&random=1270584905846&_method=get" but when it gets sent across the wire, I only have the following: authenticity_token 6GA9R_snip_253D remote 1 Why in the world is this not working?

    Read the article

  • Ruby proc vs lambda in initialize()

    - by Jimmy Chu
    I found out this morning that proc.new works in a class initialize method, but not lambda. Concretely, I mean: class TestClass attr_reader :proc, :lambda def initialize @proc = Proc.new {puts "Hello from Proc"} @lambda = lambda {puts "Hello from lambda"} end end c = TestClass.new c.proc.call c.lambda.call In the above case, the result will be: Hello from Proc test.rb:14:in `<main>': undefined method `call' for nil:NilClass (NoMethodError) Why is that? Thanks!

    Read the article

  • Ruby method Array#<< not updating the array in hash

    - by Mladen Jablanovic
    Inspired by http://stackoverflow.com/questions/2552363/how-can-i-marshal-a-hash-with-arrays I wonder what's the reason that Array#<< won't work properly in the following code: h = Hash.new{Array.new} #=> {} h[0] #=> [] h[0] << 'a' #=> ["a"] h[0] #=> [] # why?! h[0] += ['a'] #=> ["a"] h[0] #=> ["a"] # as expected Does it have to do with the fact that << changes the array in-place, while Array#+ creates a new instance?

    Read the article

  • Fusion charts free on Ruby on Rails

    - by Kiran
    Hi i am using Fusion charts free with Rail 2.3.5 I tried to simulate the single_array example provided in the documentation but instead of graph it is showing me the following message The method used is setDataXML.The XML is #Creates xml with values for sales data of products #along with their names. #The values required for building the xml is obtained as parameter arr_data #It expects an array in which each element is #itself an array with first element as label and second element as value xml = Builder::XmlMarkup.new xml.graph(:caption='Sales by Product', :numberPrefix='$', :formatNumberScale='0',:decimalPrecision='0') do for item in arr_data xml.set(:name=item[0], :value=item[1],:color=''+get_FC_color) end end Anybody seen this message before ? i am using Firefox with flash player 9

    Read the article

  • Trouble with array of dictionaries, ruby

    - by user299450
    I am getting the following error. game.rb:46:in `play': undefined method `[]' for nil:NilClass (NoMethodError) from game.rb:45:in each' from game.rb:45:inplay' from game.rb:56 with this code, def play() currentTile = nil @tiles.each do |tile| if(tile['Name'] == 'Starting Square') currentTile = tile end puts("#{currentTile['Desciption']}") end end This is part of a text adventure game, I am playing with @tiles is an array of tiles that was read from a file. Each tile is a dictionary. Thanks for any help, I cant figure this out

    Read the article

  • Ruby Regexp methods?

    - by fjs6
    Is there a gem/example_code that allows to work with regexps? I am not looking for what a regexp can do, but what can be done to a Regexp object. For example: r = Regexp.new(...) r.min_length => the minimum length of a matching string r = Regexp.new("car(less)?") r.min_length => 3 for the string "car" Thanks!

    Read the article

  • Ruby CSV in Array

    - by mattrock
    I read a CSV file. This file looks like this 1.00 cm; 2.00cm ; 3.00 cm; ... ; 100 cm 2.00 cm; 4.00 cm; 6.00 cm; ... ; 100 cm 4.00 cm; 8.00 cm; 12.00 cm; ... ; 100cm 8.00 cm; 16.00 cm; 24.00 cm; ... ; 100cm I have already written the following code CSV.foreach("/Users/testUser/Entwicklung/coverrechner/CoverPaperDE.csv", col_sep: ';') do |row| puts row[0] end This produces the following output: 1.00 cm 2.00 cm 4.00 cm 8.00 cm Example: My matrix is constructed 1.1 1.2 1.3 1.4 2.1 2.2 2.3 2.4 3.1 3.2 3.3 3.4 4.1 4.2 4.3 4.4 I want the following output 1.1 2.1 3.1 4.1 1.2 2.2 3.2 4.2 ... 4.4 How does it work?

    Read the article

  • Ruby on Rails : How can i display data for the current view from a different table

    - by krishkule
    This might be a easy-to-answer question, but its a pain in the bum for me.... So... I have two tables - Chords - |id|chord|name|rating|artist_id| Artists - |id|artist| (the relations : chords : belongs_to :artist artists : has_many :chords ) And in the index page for "chords" i want to display chord,name,rating from Chords table AND artist from the Artists table this is the code for the chrod's index.html.erb : <table border="1"> <%@chords.each do |chord|%> <tr> <td><%=chord.artist.artist%></td> <td><%= link_to chord.name, chord %></td> <td><%=chord.rating%></td> <td><%= chord.created_at %></td> </tr> <%end%> </table> The error message is : undefined method `artist' for nil:NilClass Actually, at first it worked, but when i started to create the "new.html.erb" page and the create,new controllers, it stopped working - thats why this is so confusing for me! I will be glad to hear any critique and suggestions! Thank you

    Read the article

  • [ruby] Check if file is a valid image

    - by some guy
    Hi all, I'm using rmagick to manipulate image files. I use the ImageList.new on each file to get started. When I apply this method to an invalid image file I get the below error which interrupts the execution of the script: RMagick.rb:1635:in `read': Improper image header (Magick::ImageMagickError) Therefore I would like to be able to check whether a file is a valid image file before using this method. Any ideas? Thanks.

    Read the article

< Previous Page | 161 162 163 164 165 166 167 168 169 170 171 172  | Next Page >