Ruby on Rails is an open-source web development framework optimized for programmer happiness and maintaining sustainable productivity. Many things are defined by convention, freeing you from having to re-invent things to stay productive.
1
vote
1answer
19 views
DRY up Rails Navigation Code
In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i ...
1
vote
1answer
22 views
Clean up Rails Routes
Is there any way I can DRY up this Rails 4 routes.rb code?
match '/oauth/apps/' => 'oauth/applications#index', :as => :oauth_applications, :via => :get
match '/oauth/apps/new/' => ...
0
votes
3answers
76 views
Tell me how to improve my code?
I am a redneck coder that I was not happy! How can I improve this code:
def show
if params[:type]=="all"
if params[:dir] =="next"
@work = Work.find(:first, :conditions => ["id > ? ...
4
votes
1answer
3k views
What's wrong with my spec_helper.rb for RSpec, Capybara, FactoryGirl, Spork and Devise?
Here's my spec_helper.rb
Having been through hundreds of often-conflicting posts on testing with RSpec, Capybara, FactoryGirl, Spork, Guard and Devise without Cucumber, this is the spec_helper which ...
-1
votes
0answers
45 views
New library for declaring units on numerical model attributes
A couple of days ago as I was working on a project I stumbled something I consider a problem and that, as far I know, doesn't have any good solution available in Rails.
The problem is attribute ...
1
vote
0answers
20 views
Dynamic Controller Creation in Rails
I have overrode Rails' ActionDispatch::Routing::RouteSet::Dispatcher.controller_reference method to check if a controller exists by checking for the required constants and then creating them based ...
0
votes
1answer
85 views
Refactoring create action to be valid when doing POST via json
The following code validates a PIN given to the user against a Subscription object. Since It does not respond_with(@confirm) it broke when doing POST using JSON with curl. How could I simplify this to ...
5
votes
1answer
160 views
scopes chaining by OR
How can i DRY these scopes?
scope :reputed, -> {
joins{reputations.outer}.
where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ?', LOWEST_VOTE, true]}
}
...
2
votes
1answer
62 views
Mapping arrays to ranges in Ruby
I have a simple Rails app, which is used to run some clinical surveys. Participants answer sets of questions (multiple-choice, valued 1-5), and, within each set, the answers are summed up and the ...
1
vote
0answers
25 views
Meta programming: dupping Rails model
Can someone please review my code:
# dup/ish -> //github.com/rails/rails/issues/5449
class Form
include Mongoid::Document
attr_accessor :source
def self.ish(prefix, suffix, &block)
...
1
vote
1answer
125 views
How to refactor my controller specs?
In my project (https://github.com/GCorbel/comment-my-projects) I have this kind of code to test my controllers.
#encoding=utf-8
require 'spec_helper'
describe ProjectsController do
let!(:project) ...
1
vote
1answer
173 views
Rails feed parser to be improved
This is my feed parser method using feedzirra. It works but I feel dirty because I can't figure out how to better this code. Any suggestion?
class Feed < ActiveRecord::Base
attr_accessible ...
2
votes
1answer
50 views
How do I refactor this ActiveRecord object to lessen dependency on callbacks?
I have an Order object that belongs_to a BillingAddress and a ShippingAddress. I want to present my user with only ShippingAddress fields and a checked checkbox indicating that the billing address ...
3
votes
1answer
202 views
Ruby Rails - Snippets from a project that don't seem so eloquent
I'm brand new to both Ruby and Rails, and while all the following works, it seems a bit messy.
This is on a classified model to generate WHERE/AND WHERE clauses based on whether or not the user ...
1
vote
0answers
24 views
Review of helper method that adds some divs
The following code ended up to be ugly and I can't find a way to make it better. Any comments will be very appreciated.
The expected HTML output is this (it is working, the output is just for ...
2
votes
2answers
176 views
How render from a FormBuilder
I'm starting Rails and Ruby for a short time. But I try to make it the cleanest way I can.
So, in an attempt to clean my view I try to custom my FormBuilder.
Like this :
# ...
3
votes
1answer
133 views
Nasty Age Printing Method
I have this ugly age printing method. Can you do better?
def age(birth_date)
today = Date.today
years = today.year - birth_date.year
months = today.month - birth_date.month
(months -1) if ...
0
votes
1answer
66 views
Math Calculus in ruby
I have several calculus to do in my ruby app.
My code is currently working but I find it very ugly.
@guestreviews = GuestReview.where(:reviewed_id => @user.id)
@hostreviews = ...
1
vote
1answer
61 views
Rails: Setting a transient attribute on a set of objects from one model based on information from a junction model
I have a user model, a task model, and a junction model user_task that saves the data joining the two:
class Task < ActiveRecord::Base
attr_accessor :completed_on
has_many :user_tasks
class ...
-1
votes
1answer
70 views
How to create 3 objects using one form only if each one is valid? [closed]
I want to create Job, Employer and Company using one form.
Model
class Job < ActiveRecord::Base
accepts_nested_attributes_for :company, :employer
belongs_to :company
belongs_to :employer
...
1
vote
4answers
73 views
can this rails code be simplified and be more efficient? nested if else statements
Here's a part of my controller and it's getting quite lengthy (the code works).
Would this code slow down the performance of my website? Can it be cleaned up and be written more efficiently?
def ...
3
votes
2answers
108 views
How would one more elegantly parse data from XML using Ruby and Nokogiri?
I have a method that parses XML into an array of hashes.
Here is the original XML:
<rowset name="skillqueue" key="queuePosition" ...
2
votes
1answer
118 views
Refactor Rails middleware initialization block
I'm working on a simple superfeedr powered rails app here.
Based on the superfeedr-rack gem documentation, I'm doing this to initialize the middleware (snippet from application.rb config block):
...
1
vote
0answers
26 views
Converting data in a Rails Migration using the model
Lets imagine we have an Article entity, with data imported from a legacy database. It contains an appendix column with type integer. This column is always filled with values 0, 1 or nil, so we decide ...
0
votes
1answer
41 views
Rails 3: Create method with association?
In Rails 3, I have two models, Nutrient and Recommendation. Nutrient has_many Recommendation, Recommendation belongs_to Nutrient. I am trying to implement the create method of the recommendation in ...
0
votes
1answer
33 views
What is the best way to format a large has_many through line?
This question is about code style.
I have this line in one of my models:
has_many :owning_artists, :through => :artist_tracks, :source => :artist, :conditions => { :artist_tracks => { ...
2
votes
3answers
72 views
I need help refactoring some Rails code that looks clunky.
I would like to refactor this block, it looks clunky:
# refactor me
receive_payment_on = false
config[:sections].each do |section|
if section[:applicants]
section[:applicants][:sections].each ...
2
votes
1answer
54 views
two or more render/redirect in the same method
I often have method like this one with two or more render to do due to catching the error for example.
I currently do something like this:
def update
@user = current_user
if ...
0
votes
1answer
68 views
Underscore-case version of ActiveRecord model's name
Is there a better way to get the underscore-case version of an ActiveRecord model's name? So far this works, but it's far from ideal:
my_active_record_instance.class.name.underscore
1
vote
1answer
91 views
Rspec Request always break when teammate push some changes, how to improve?
This is my rspec integration test for user , it always break when my teammate change something , how do i improve this?
describe "Users" do
before(:each) do
populate_role
end
describe ...
0
votes
1answer
31 views
Ruby on Rails Single Table Inheritance [closed]
I'm trying to set up single table inheritance in Rails. I have single table called Finances, with a type set to Income or Expense.
My code is here: https://gist.github.com/caser85/5096447
Ok, I got ...
3
votes
2answers
94 views
Can I improve the way this model RSpec is written?
I'm new to RSpec and testing in general. I've come up with a spec for testing my Content model and I need some feedback 'cause I think there are many improvements that can be done. I don't know if the ...
2
votes
1answer
49 views
Rails helper method refactor
I have this messy helper method:
def gesture(klass, item, text, desc)
element_class = klass.to_s + " gesture"
content_tag :li do
if klass == :sell
link_to new_reply_path(item_id: ...
2
votes
1answer
43 views
Calculate sum of price on distant relation
If i have a booking, with a method total, which calculates the total price of the booking from the sum of all the prices of activities that belong to appointments, where a booking hasmany appointments ...
2
votes
1answer
44 views
Refactor Ruby ActiveRecord importing library
In my Rails app I need to import some files from CSV and Excel files. I needed it in 2 models so I have written lib/importable.rb:
module Importable
def self.included(base)
base.send :extend, ...
3
votes
2answers
1k views
RSpec integration tests for a simple Rails API
The Model is simple. A Player class with three attributes: first_name, last_name, and team_id.
I'm just trying to get a handle on TDD for what will expand into a much more robust API. Below is my ...
3
votes
1answer
111 views
Rails: Retrieve all parents, all possible children, sorted and with their “depth”
I have a model section with a column parent_id - the only thing identifying a parent/child relationship. I wrote a helper method to output all sections, all their possible subsections and include ...
1
vote
1answer
92 views
How can I make this code DRY and KISS in my model?
class Rating < ActiveRecord::Base
attr_accessible :item_type, :item_id, :rating, :voters_up, :voters_down
serialize :voters_up, Hash
serialize :voters_down, Hash
belongs_to :ranks, ...
3
votes
2answers
82 views
How can I make this code DRY in my controller?
What is the best way to DRY this code up?
class NotificationsController < ApplicationController
before_filter :load_user
def unsubscribe
if @facebook_admin && ...
3
votes
2answers
108 views
An abundance of ternary operators
I'd like to find a way to do what this method does in a cleaner, less hacky looking way
def self.create_from_person!(person)
spi = new(:person => person, :provider => person.provider)
...
0
votes
1answer
152 views
Why did I fail this Ruby developer test? [closed]
I took this developer test for a potential employer, and they said I failed because of my response to the first question. But Rails for Zombies seemed to imply that that's how you assign data to ...
2
votes
3answers
221 views
Refactoring if statement
Is there a better way to do this? im kinda ending up having a lot of if statements. Any hints would be great!
if params[:custom_url] || params[:user_id]
if !params[:user_id].blank?
@user = ...
2
votes
1answer
23 views
How to refactor that content_tag adding method?
How to get rid of that duplicaiton in if conditional?
def set_caption(result)
if result.respond_to?(:app_name)
content_tag(:div, result.type_name, class: 'type-name') +
content_tag(:div, ...
1
vote
1answer
60 views
Updating / validating mass update rails association
My recipes model is as follows
has_many :quantities
has_many :ingredients, :through => :quantities, :uniq => true
has_many :sizes, :through => :quantities, :uniq => true
And the ...
3
votes
3answers
95 views
Best way to include image_tag inside link_to
What is the most elegant and readable way to in include (potentially long) image_tag calls inside of link_to?
Example
<%= link_to image_tag('buckminsterfullerene.png', width: '210', height: '60', ...
4
votes
2answers
181 views
Carousel code review
Is there a better way to implement my carousel in less lines? Currently my solution is:
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<% ...
2
votes
2answers
96 views
Placement of success code in a conditional
I'm not sure if there's a standard view where the placement of a success result should be in a conditional that can return multiple statuses. The success condition of this function is in the middle of ...
0
votes
2answers
62 views
Refactoring a HTML class collector?
I have following HTML class collector. Is there a better way than []tap for this?
def tr_classes(user)
classes = [].tap do |c|
c << "error" if user.company.nil?
c << "disabled" ...
4
votes
1answer
106 views
Refactor ruby each-code
def users_list
html = ''
self.users.each do |user|
html << user.link_avatar_tag
end
html.html_safe
end
I feel that it is possible to write shorter.
Is it possible ...
1
vote
1answer
38 views
Refactor specs for service class methods
Service Class
# services/search.rb
class Search
include Rails.application.routes.url_helpers
include ActionView::Helpers::TagHelper
def initialize(term, app_ids)
@term = term
@app_ids ...

