Where to put this kind of calculation in Rails? - ruby-on-rails

I have started to learn ROR and come along with creating one simple application.
Basicly the app uses calculation for the difference in months between today and another date stored in the database. I have no idea where is the most convenient way to put this kind of code.
Currently, is placed in the view where i subtract today from the date in the database :
#user.html.erb
Month difference : <%= (Date.today - #user.date_signed).to_i/30
and controller :
class UserController < ApplicationController
def user
#user = User.find(params[:id])
Is there any better way i can accomplish the same ? And if so how ?
Thank you

It belongs in the model, since you want to handle it as another attribute of user.
class User < ActiveRecord::Base
def months_since_signed
(Date.today - self.date_signed).to_i/30
end
end
Then, in your view, just call the method with the instance of User as the receiver.
Month difference : <%= #user.months_since_signed %>

Related

Ruby on Rails devise, how to put a limit on how often a user can change their username

`I have recently started working on a rails app and using devise as authentication. but I have ran into a wall. I would like to know if there's a way to set a period limit on how often a user may update their username. For example, if a User update their username today, they shouldn't be able to update it again until a 30day period has passed.
I have looked through devise docs, but nothing address that functionality, I have also search SO and the web but to no avail.
Any help would be very much be appreciated on how to go about it, or at least be pointed in the right direction. Thanks in advance!
I have added to the user model
after_save :name_last_updated
def name_last_updated
if self.username_changed?
self.name_last_updated_at = Time.now
end
but this does not update the colunm name_last_updated_at. any clues of what i am doing wrong will be helpful ^^ thanks!
so, after messing around with a few codes i figured an alternative way to go about this. I created a new column to track new time the user should be able to see the form to update his username.
def username_next_update
self.username_next_update_at = self.username_last_update_at + 2.minutes
end
for learning and testing purposes i added +2.minutes
and i did a before_save on it.
In my view i wrapped it around an if and else statement although i am quite confuse with the logic.
<% if current_user.username_next_update_at < time.zone.now %>
********
<% end %>
but i expected to it to work only if it was > sign instead of <. any tips will be helpful or any better alternatives :)
You need to create it from scratch.
Create a new column in the users table, call it name_last_updated, when the user updates their name for the first time, set that column to today's date. then every time a user wants to update their name, check that column and compare with today's date and see if 30 days have passed:
if Date.today - user.name_last_update < 30
#display error
end
We can use user updated_at column created by the devise gem and add a callback method in the user model to make sure that we call this method every time the user model is updated.
before_update { |user| user.write_attribute if user.is_permitted? }
def write_attribute
self.user_name = params[:user][:user_name]
end
def is_permitted?
if self.username_changed?
Date.today - updated_at < 30
end
end
You should use the before_update and specify which record has to activate the callback instead of using after_save.
I would do something like this:
before_update :name_last_updated, if: :username_changed?
def name_last_updated
if (self.name_last_updated_at.to_date + 30.days) < Date.today
self.update(name_last_updated_at: Time.now)
end
end

How to use the new ActiveSupport::Testing::TimeHelpers inside controller

Edit to make it more clear
Like the title tells how to use the awesome ActiveSupport::Testing::TimeHelpers#travel_to method inside my controller. Like in tests, I want to achieve something like this:
SomethingConroller < ApplicationController
def index
travel_to some_date do
# some stuff that it depends on the current_date
end
end
end
Tried include the module:
include ActiveSupport::Testing::TimeHelpers
but I got:
uninitialized constant ActiveSupport::Testing
Hoping that the date traveled to will be applied to the view, view_helpers, controller_action
If you must, then add require 'active_support/testing/time_helpers' at the top of the file.
Although I've no idea what you're doing with that code. Try this instead:
SomethingConroller < ApplicationController
def index
#instance = SomeModel.find_by_date(12.days.ago)
end
end
I think you're messing up your concepts here. You should use time travel to put tests in a certain time so that you can test a scenario at that new time. For example, lets say users have to renew their subscription after one year.
create the user(now).
travel to the time a year from now
Make sure that when the user logs in at travelled to time they are duly notified.
To manipulate date for queries, use 12.days.ago, 12.days.from_now, this can be used with seconds,days, minutes, years

How to prevent actions at specific date and time?

I would like to allow the users to 'create' and 'update' their submissions (bets) until a specific date and time at which point their bets are final (can no longer be created or updated). This process would repeat each week.
I'm fairly new to Rails and I'm not sure if there is a term for this or what to search for.
Can anyone point me in the right direction?
Probably the easiest way to achieve this is just to add a before_filter (Rails 3.x) or before_action (Rails 4.x) to your controller. You can do so like this:
Assume you have submissions_controller.rb with create/update actions like so - add a before filter that will only apply to the create and update actions. You can then implement a private method in the controller to redirect the user back to your root_path or elsewhere and give a flash message as to why.
class PagesController < ApplicationController
before_filter :check_if_bets_are_final, :only => [:create, :update]
def create
...
end
def update
...
end
private
def check_if_bets_are_final
if Time.now >= Time.new(2014, 02, 20)
flash[:error] = "You can no longer modify or submit new bets!"
redirect_to root_path
end
end
end
Aside from your controller action though, it will probably be safer to implement a model-level validation/check to reject it if the date is past, just to be safe (or if you have other ways to update that object in the future). You can do this through the model hook before_save, in which you can pretty much do a similar check that I have given above.
Also, the other caveat is that comparing Time.now could be in a different timezone depending on where your server is. Just be cognisant of this when you do your checks, and cast the time properly with this in mind.
Since you didn't provide a specific implementation, I'm not quite sure if you're having trouble specifically with Ruby or Rails. However, given your question, I would store a datetime variable in your database when the user creates the bet. Every time the user tries to 'update' the bet, check in the database whether or not it's been past that specific time away from the bet creation. Hope this helps.

Create a logic captcha from scratch

I haven't touched a scrap of code yet, but here's my thoughts on how to do this:
Create a :interactions entry in my session hash. This will contain an array of time stamps. Every time a user goes through any action, the time they did this will be appended to the :interactions entry. The array will be initialized in my sessions controller, and timestamps appended to it via a filter in my application controller:
class SessionsController < ApplicationController
def create
create_session
session[:interactions] = []
end
end
class ApplicationController < ActionController::Base
after_action :log_time
private
def log_time
session[:interactions] << Time.now.to_i
end
end
Then, create another action in my application controller, the one tasked with launching the recaptcha if the user's behaviour is suspicious. All it does is see when we have 20 entries in our session[:interactions] array, find out the time elapsed between each pair of consecutive entries, and then find the average time elapsed between these interactions. If the average time is under two minutes, the recaptcha is launched. The session[interactions] array is then reset.
class ApplicationController < ActionController::Base
after_action :log_time
before_action :launch_captcha
private
def launch_captcha
if session[:interactions].length == 20
elapsed = []
session[:interactions].each_slice(2) do |a, b|
elapsed << b - a
end
total = elapsed.inject(:+)
average = total / 20
if total < 120
# this a part I'm really not sure how to do:
# various instance variables should be populated here
redirect_to 'application/launch_captcha.html.erb'
end
session[:interactions] = []
end
end
def log_time
session[:interactions] << Time.now
end
end
Now, the fact the session[:interactions] is reset may be a bit of a weakness; all bets are off for those twenty interactions. But I want to build on the above logic, maybe add session[:captchas_sent], to the session hash (or even have captchas_sent as a column and save it to the user's record), and if the session[:captchas_sent] is x amount or y amount, warnings or temporary bans could come into effect.
What are your thoughts on the above way of monitoring user behaviour?
Here's where my knowledge of rails is starting to break down though. Once I've redirected the user to the recaptcha page, how should I proceed? I have two tables, questions and answers with a has_many belongs_to relationship between them respectively.
So a random question will come from my questions table, and then I'll have a form that pertains to an answer. It will be an ajax form, and have just one field, a text field for the answer. The action the form links to, human test, will see if the answer given is equal to one of the question's answers. But how should the question's id be passed into this action? It couldn't be a simple hidden field, because once the spammer knows the answer to one question, his script could always set the id to that one question. So the params hash or the sessions hash maybe? I need some advice here guys.
I also don't really know how the human test method should proceed once the it finds the user's answer is equal to one of the question's answers:
Let's say the user is submitting a comment. They fill in the comment, hit the submit button, the launch_captcha action kicks in, and redirects them to 'application/launch_captcha.html.erb'. What has happened to the data in the comment create form? Once they've answered the captcha correctly, how should the human_test method proceed? How could it go on to submit their comment as usual? I just don't know how to do that...I need to create an action that is called before the create action of a form...and..argh I just don't know. Help guys!

Order column using calculation and class method

I am building an app that allows users to post. Those posts can be upvoted and downvoted. Each post record keeps track of upvotes:integer and downvotes:integer. I want to be able to order the records by which has the most upvotes total (in other words: upvotes-downvotes). I have absolutely no idea how to do this because I do not quite understand how Class methods interact with the object they are called on. This is my attempt:
My controller:
def index
#posts = Post.find(:all).most_votes.order(vote_difference)
end
My Post.rb Model:
def self.most_votes
vote_difference = (upvotes-downvotes)
end
Any ideas on how to do this?
Turns out you can actually insert the calculation right into the .order() value:
#posts = Post.find(:all).order('upvotes + downvotes')

Resources