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
14 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
88 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
51 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
23 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
108 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
33 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
68 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
53 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
27 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
98 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
53 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
46 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
35 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
32 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
40 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
87 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
79 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
136 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
103 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
20 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
50 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
86 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
84 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
167 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
99 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
95 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
1answer
34 views
How to create 3 objects using one form only if each one is valid?
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
105 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
36 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
61 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
39 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
47 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
116 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
90 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
215 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
106 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
110 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
50 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 %>
...
1
vote
0answers
39 views
Duplicate sql code in controller
How i can rewrite or refactoring my code in controller. I have the same sql query ( @plan_gp_users) in all def.
class PlanGpsController < ApplicationController
def index
@search = ...
0
votes
1answer
35 views
Reuse object in model in Rails
Using Rails 3.2. I have the following code:
# photo.rb
class Photo < ActiveRecord::Base
after_create :associate_current_user
after_save :increase_user_photos_count
after_destroy ...
2
votes
1answer
149 views
Rails 3: How can I improve this ActiveRecord count
Here I retrieve a collection of causes from the database. Along with the information from each cause, I want to send the number of users in each cause. This way works, but if experience has told me ...
2
votes
0answers
70 views
Rendering hidden element from view in Rails, HAML
Simple example, I need to render div with some text hidden by default. I'll do something like:
= link_to 'Display text', '#'
.div_with_text{ style: 'display: none;' }
= 'Some text!'
And after ...
1
vote
1answer
31 views
Bug with cronjob and log building
I have a cronjob starting a ruby script (in a rails environment) at the beginning of each hour. The ruby script then makes a series of SQL queries, and looks like this:
def hourly_job
time = ...
1
vote
1answer
128 views
How to render partials dynamically in Rails 3
Here's a simple one for you guys. My User model has multiple roles (utilizing CanCan). Each role's dashboard view is different enough to warrant a partial for each role (admins get big-picture reports ...
2
votes
1answer
111 views
Refactoring a Complex Create Action in Rails 3.2
I posted a question last week about refactoring an after_create callback. The code in this question is for the create action. I'm using Stripe to handle credit card payments and am roughly following ...
1
vote
1answer
99 views
Improve on an after_create callback with database queries - Ruby on Rails
First, some background. I have a Payment model that has_many :subscriptions. When a user pays (creates a new payment), I have an after_create callback that adds the newly created @payment.id to ...
2
votes
2answers
980 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
0answers
107 views
Rails partial inheritance hack
I have a STI table and want to be able to render a collection using
render @collection
with every elements of the collection using their own partial or, if they don't have one, the parent ...
1
vote
2answers
121 views
Multiple ORs in if-else
How do I refactor this in Rails?
if formatted_address.blank? || country.blank? || lat.blank? || lng.blank?
...
end
If I have 10 attributes to check if blank, I don't wanna retype .blank? 10 ...