attribute writer display password - ruby-on-rails

I'm just starting to learn ruby on rails and using
http://ruby-for-beginners.rubymonstas.org/writing_classes/attribute_writers.html
The article doesn't explain how to display the password
Here is my code.
class Person
def initialize(name)
#name = name
end
def name
#name
end
def password=(pass)
#password = pass
end
def greet(other)
puts "Hi " + other.name
puts "Your password is " + #(how do i call password here?)
end
end
person = Person.new("Lee")
person.password = ("super secret")
person.greet(person)
p person
I'm not understanding attribute writers at this point.
Can anyone help me?
Thank you so much

While you have already set class variable #password = pass
You are able to call it as #password, remember if password wasn't set, it will give an error.
def greet(other)
puts "Hi " + other.name
puts "Your password is #{#password}"
end
person = Person.new("Lee")
person.greet(person) #will give an error
person.password = "pass"
person.greet(person) #will print the password

Related

Official email validation in Ruby

I only want official email addresses such as xyz#company.com to sign up on my service rather than other generic email addresses such as gmail.com or Yahoo mail.com
Is there a ruby gem to achieve this kind of email validation? If not, how to make this happen?
You could write a custom validation in the appropriate model as shown here: http://www.rails-dev.com/custom-validators-in-ruby-on-rails-4
The basic idea in the article is as follows:
Make your validation method, and put it in a new directory called 'validators'
# app/validators/email_validator.rb
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^#\s]+)+#yourdomain.com\z/i
record.errors[attribute] << (options[:message] || "wrong email address")
end
end
end
(I have not tested this regex! Please use something like http://rubular.com/ and plug in your own email domain pattern to make sure it's working correctly.)
Then make sure Rails knows to load the new validators directory:
# config/application.rb
config.autoload_paths += %W["#{config.root}/app/validators/"]
Then add the new validation (email) to the appropriate model:
#MyModel.rb
validates :my_email_field, email: true
There is a free MailboxValidator web service that you can perform real-time email address validation in Ruby.
https://github.com/MailboxValidator/mailboxvalidator-ruby
require "mailboxvalidator_ruby"
apikey = "MY_API_KEY"
email = "example#example.com"
mbv = MailboxValidator::MBV.new()
mbv.apikey = apikey
mbv.query_single(email)
if mbv.error != nil
puts "Error: #{mbv.error}"
elsif mbv.result != nil
puts "email_address: #{mbv.result.email_address}"
puts "domain: #{mbv.result.domain}"
puts "is_free: #{mbv.result.is_free}"
puts "is_syntax: #{mbv.result.is_syntax}"
puts "is_domain: #{mbv.result.is_domain}"
puts "is_smtp: #{mbv.result.is_smtp}"
puts "is_verified: #{mbv.result.is_verified}"
puts "is_server_down: #{mbv.result.is_server_down}"
puts "is_greylisted: #{mbv.result.is_greylisted}"
puts "is_disposable: #{mbv.result.is_disposable}"
puts "is_suppressed: #{mbv.result.is_suppressed}"
puts "is_role: #{mbv.result.is_role}"
puts "is_high_risk: #{mbv.result.is_high_risk}"
puts "is_catchall: #{mbv.result.is_catchall}"
puts "mailboxvalidator_score: #{mbv.result.mailboxvalidator_score}"
puts "time_taken: #{mbv.result.time_taken}"
puts "status: #{mbv.result.status}"
puts "credits_available: #{mbv.result.credits_available}"
puts "error_code: #{mbv.result.error_code}"
puts "error_message: #{mbv.result.error_message}"
end

Array not saving user input in ruby

This is what I have so far, but the array is not saving the first value if the user enters 2 or more car types. If I remove the car.get_ methods the program runs fine without saving the users input. Is there a method I am missing?
class Cars
def set_make(make)
end
def set_model(model)
end
def set_year(year)
end
array_of_cars = Array.new
print "How many cars do you want to create? "
num_cars = gets.to_i
puts
for i in 1.. num_cars
puts
print "Enter make for car #{i}: "
make = gets.chomp
print "Enter model for car #{i}: "
model = gets.chomp
print "Enter year of car #{i}: "
year = gets.to_i
c = Car.new
c.set_make(make)
c.set_model(model)
c.set_year(year)
array_of_cars << c
end
puts
puts "You have the following cars: "
for car in array_of_cars
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
end
Ok so the primary issue is that you calling the Car.new where the Car class is defined. You should not have an array of cars in the car class. You could try creating a Dealership class that has an array of cars then you could do something like this
class Dealership
attr_accessor :car_lot
def initialize
#car_lot = []
end
def add_car(car)
#car_lot << car
end
end
crazy_carls = Dealership.new
car1 = Car.new(make, model, year)
crazy_carls.add_car(car1)
crazy_carls.car_lot.each do |car
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
You need to refactor the car class a good deal first though, look into how to use the initialize method, attr_accessor, and instance variables.

Rotten Tomatoes API with Ruby

I'm new to Ruby & trying out this API. I want to build a simple game which asks an user for two movies names to guess / compare which one received a better audience rating or any other comparative parameter. The API is working and I tried substituting the code with the user input but that's where it breaks down. (I have also mentioned the class I am calling)
require_relative 'workspace/lib/select'
require_relative 'workspace/lib/brand'
require 'json'
require 'rest-client'
# puts "hello world"
def create_reviewer
puts "What is your name?"
name = gets.strip
puts "So, #{name} what genre are you interested in?"
genre = gets.strip
Select.new(name, genre)
end
def create_brand
puts "Enter the first brand"
brand_a = gets.strip
puts "Enter the second brand"
brand_b = gets.strip
Brand.new(brand_a, brand_b)
end
review = create_reviewer
brands = create_brand
def get_rotten_tomatoes
response = JSON.load(RestClient.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=SECRET&q=#{brand_a}&page_limit=30'))
response["movies"].map do |entry|
brand_a = entry["ratings"]["audience_score"]
brand_b = entry["ratings"]["critics_score"]
final_score = {brand_a: audience_score, brand_b: critics_score}
final_score
end
goodies = get_rotten_tomatoes
puts goodies
----
class Brand
attr_accessor :brand_a, :brand_b
def initialize(name, genre)
#brand_a = brand_a
#brand_b = brand_b
end
# def to_s
# "Tenant: #{#name} \n Credit Score: #{#credit_score}."
# end
end

Rails rspec after_save reference self

I want to add a profanity check on my website.
I'm taking a TD approach and I'm trying the following:
check if profanity exists in specific profile fields
create a flag
create a flag if one does not exist
create a flag if one exists, but has been dismissed
Here is my spec so far:
describe Painter do
before do
#painter = FactoryGirl.create(:painter_flag)
end
context "blacklist flag" do
it "check if profanity exists" do
#painter.experience = "test"
#painter.save
expect {#painter.blacklist_flags?}.to be_true
end
it "create flag if profanity exists" do
#painter.experience = "test"
#painter.save
BlacklistFlag.count.should be > 0
end
end
end
Painter related code:
after_save :create_flag, if: :blacklist_flags?
def blacklist_flags?
list = ""
list << skills
#list << experience
#list << first_name
#list << last_name
#list.downcase.scan(/(badword|badword)/).size > 0
end
def create_flag
end
If I comment out the following code above the two test pass:
list << skills
When I leave the code in I receive the following error:
2) Painter blacklist flag create flag if profanity exists
Failure/Error: #painter = FactoryGirl.create(:painter_flag)
TypeError:
can't convert nil into String
It seems there's a problem with referencing self because skills, experience, etc are part of the model. I'm not sure how to fix this. Please advise.
Update:
FactoryGirl.define do
factory :painter do
first_name "Brian"
last_name "Rosedale"
state "OH"
zip_code "43081"
sequence(:email) {|n| "nobody#{n}#painterprofessions.com" }
phone "12345566"
pdca_member false
password "123456"
factory :painter_flag do
skills = "badword"
end
end
end
Just use this line in your factory for :painter_flag, without the = sign.
skills "badword"
I think what's causing the error is because the callback is been executed on the line #painter = FactoryGirl.create(:painter_flag).
You might want to use FactoryGirl.build method if you want to test the callback.

Creating a FullName method in the Devise User Model?

right now I use devise and have two fields. fname and lname.
I would like the ability to put a full_name field to the user model. Then the user model would take the full_name field and extract the fname and lname by splitting with a space. if there is more than one space that would all go to the fname and the last item would be the last name, and then saved to the user model with the extracted fields for fname and lname.
Is this possible without hacking up devise?
Thanks
The problem with both current answers is that they don't handle three(+) word names such as Billy Bob Thornton.
'Billy Bob Thornton'.split(/(.+) (.+)$/) => ["", "Billy Bob", "Thornton"]
'Billy Bob Thornton'.split(' ', 2) => ["Billy", "Bob Thornton"]
The original posting requests all but the last name to go to first name. So I'd suggest:
def full_name
[first_name, last_name].join(' ')
end
def full_name=(name)
elements = name.split(' ')
self.last_name = elements.delete(elements.last)
self.first_name = elements.join(" ")
end
You don't need to hack up devise persay, just do it in your Users model (or whatever modal you are usuing as your devise_for
class User
def fullname
self.fname << " " << self.lname
end
def fullname=(fname)
names = fname.split(/(.+) (.+)$/)
self.fname = names[0]
self.lname = names[1]
end
end
untested and off the top my head, but it should be a start....
i wouldn't suggest storing the fullname, just use it like a helper function, but that is up to you.

Resources