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.
0
votes
0answers
7 views
General thoughts on the style of this rspec-rails test
Here's a test from a Rails app I'm working on. I want to know if I'm using describe, let, before, expect, etc in the proper way. Any feedback is appreciated:
It is an integration test using capybara ...
1
vote
1answer
34 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
27 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
85 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 > ? ...
-1
votes
0answers
46 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
21 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 ...
1
vote
0answers
27 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)
...
2
votes
1answer
51 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 ...
2
votes
1answer
63 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
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 ...
0
votes
1answer
67 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
62 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 ...
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 ...
1
vote
4answers
74 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 ...
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 ...
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):
...
0
votes
1answer
42 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 ...
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
32 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
111 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" ...
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
2
votes
1answer
51 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 ...
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
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, ...
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 && ...
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 ...
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)
...
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', ...
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 ...
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">
<% ...
3
votes
1answer
113 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 ...
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 ...
-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
...
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 ...
0
votes
2answers
63 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" ...
0
votes
1answer
41 views
Has many through relationship needs code review
Having an issue optimising has_many through relationship
To quickly introduce I have Setting model and Notification model (that is mainly used as a storage of all notification types).
They have ...
1
vote
0answers
55 views
Working on the Rails project alone. Need code review
Working on the Rails project where I have many-to-many :through relationship.
Quickly introduce you to the code base: each setting has many notifications through email_notification model where the ...
2
votes
0answers
149 views
Moving from Solr (Sunspot) to ElasticSearch (Tire), Review needed
I would like a review regarding the following code in which I index and search the City model. Currently both solr (with sunspot gem) and elaticsearch (with the tire gem) are show. I am migrating from ...
4
votes
2answers
95 views
Refactor highlight matched word in string
I have following method which highlight matched word in text:
# Hightlight matched term
#
# Ex(for term: some):
# "<span class="bold">Some</span> CEO Event"
#
def ...
4
votes
2answers
292 views
ElasticSearch, Tire - refactor autocomplete method for multiple resources
I am using ElasticSearch and Tire for search in my app across all models.
I would like to refactor autocomplete method because it looks to complex for me.
Am I using a good pattern for searching ...
1
vote
1answer
107 views
Refactor or simple code RoR
I have a GiftCard class where I have method can_deliver? and deliver! that I think can be refactored to better looking code :
def can_deliver?
(self.sent_at.nil? && ...
2
votes
1answer
48 views
How to refactor this complicated html generator in Ruby?
['content', 'answers', 'comments'].each do |t|
break if results.length >= MAX_RESULTS
Question.search_tank('', :conditions => conditions.merge(t => "#{search_term}"), :page => 1, ...
2
votes
3answers
114 views
Simple: Need help refactoring this awkward looking method
I need help refactoring this method. It is way too long.
def report_total(feed_event, advisor)
count = 0
advisor.activity_feed_events.each do |lead|
if lead == SignupFeedEvent
...
0
votes
2answers
52 views
Refactor if function in ruby/rails [closed]
working on a rails app that doesn't seem to want to run 'Until' or 'While' functions. Having to do the following:
<% if q == 2 or q == 5 or q == 8 or q == 11 or q == 14 or q == 17 or q ==20 %>
...