Okay so I am trying to create an object for each found email domain in a text file. So far I have the matching system working and now have ran into a problem creating the objects on the fly. Here is what I got so far.
# domain = emails domain name (e.g. 'example.com')
# Agency = class for domain
if (domain + "Object").nil? == false
domain = Agency.new(domain + "Object")
#agencyList << domain
domain.addEmail(match)
puts "false"
elsif (domain + "Object").nil? == true
domain.addEmail(match)
puts "true"
end
end
end
So basically I want to check if the email domain already has an object created for it. If it doesn't, create an object using the domain name and send the matched up with the object method addEmail. If it does send the match to object method addEmail. I don't want to use hashes because I want the matches in separate arrays.
I have tried many things and I think I am in over my head. This is my first ruby script. Any help would be greatly appreciated.
I think you just want to check whether the object is in your agency list. Something like:
if #agencyList.any? {|agency| agency.domain == domain }
agency = Agency.new(domain)
#agencyList << domain
agency.addEmail(match)
puts "false"
else
domain.addEmail(match)
puts "true"
end
Related
I had a previous question that helped me loop through all users where a certain question is met.
However, I'm realizing I can't hard code that condition. I need to somehow get that data from the submitted form, which doesn't seem to be possible in the mailer.
In other words, I'm trying to loop through all users where the user's state is equal to the home_state of the candidate being entered. Basically when the candidate is created, I want to get the home_state of that candidate, and then loop through all users, and for each user that has same state as that candidate, I want to send them the email via this mailer.
Here's my candidate_mailer.rb file
class CandidateMailer < ApplicationMailer
default from: 'wesleycreations#gmail.com'
def self.send_request(row)
#candidate = Candidate.new(candidate_params) # if I can access this here, how to I create the
# following array?
emails = []
User.where(state: #candidate.home_state).each do |u|
emails << u.email # To insert the user email into the array
end
emails.each do |email|
new_request(email,row).deliver_now
end
end
def new_request(email, row)
#candidate = row
mail(to: email, subject: 'New request')
end
end
But the
#candidate = Candidate.new(candidate_params)
obviously doesn't work because the params aren't available in the mailer.
Here in the candidates_controller.rb I have this
def create
#candidate = Candidate.new(candidate_params) #of course here I can access params
if #candidate.save
row = #candidate
CandidateMailer.send_request(row)
else
render('new')
end
end
SO the question is, how do I access params in rails mailer? And if I can't, then how do I refactor my code so that the lines that check if the user meets certain condition is done in the controller?
I was able to figure this out by doing this. after I saved the candidate, I saved the candidate to a global variable. and THEN I send the mailer.
def create
#candidate = Candidate.new(candidate_params)
if #candidate.save
row = #candidate
$candidate = #candidate
end
CandidateMailer.send_request(row)
else
end
end
This way the mailer had access to the new candidate that been created, and I was able to check my condition in there.
So in my mailer, when I use $candidate.home_state, it returned the correct state, mail went out, and made me very happy :)
emails = []
User.where(state: $candidate.home_state).each do |u|
emails << u.email # To insert the user email into the array
end
I currently generate a user's profile page using their serial ID, like so:
get '/users/:id' do
#user = User.get(params[:id])
end
This works great, until a number is entered that doesn't exist in the database.
I'm aware I can change User.get to User.get! to return an ObjectNotFoundError error if the record isn't found, but I'm not sure how I can use this to my aid.
I used to use .exists? when using RoR.
Any suggestions?
Thanks in advance!
Edit: I'm going to leave the question unanswered, as I haven't actually found a solution to what I asked in the title; however, I did manage to solve my own problem by checking to see if the :id entered is higher than the amount of users that exist in the database, like so:
if params[:id].to_i > User.count
"This user does not exist."
else
#users_id = User.get(params[:id])
erb(:'users/id')
end
You already have the correct code:
#user = User.get(params[:id])
If no user exists with the given id, then #get will return nil. Then you can just do a conditional:
#user = User.get params[:id]
if #user
# user exists
else
# no user exists
end
This is a very common pattern in Ruby which takes advantage of the "truthiness" of anything other than false or nil. i.e. you can say if 0 or if [] and the condition will evaluate to true
You can recreate a .exists? method:
class User
def self.exists?(id_or_conditions)
if id_or_conditions.is_a? Integer
!! User.get id_or_conditions
else
!! User.first id_or_conditions
end
end
end
#get is similar to #find in rails, except it doesn't raise an error if the record is not found. #first is similar to #find_by in rails.
I am new to ROR.I am working on spree gem extension. I want to make email template dynamic means the content of html.erb file should store in database table .On shooting mail, all data and dynamic data are managed..?? Is it possible in ror and how to achieve this.??
Yes you can do like this just replace dynamic variables in DB like this:
You have successfully placed Service Request No. {service_requests_id} for {service_requests_category} . Our representative will be in touch with you soon for the same. Thank you." This string is store in database.
and create a helper
def replace_dynamic_variables(str,variables=nil)
variables.each do |k ,v|
str = str.gsub('{' + k.to_s + '}',v || "")
end
return str.html_safe
end
and on mailer prepare variables like:
class yourMailer < ApplicationMailer
def send_service_email(args) # email sending method
#variables = {}
# Other code like subject, to, from etc.
#db_string = #string you get form DB
#variables[:service_requests_id] = #service_requests.id
#variables[:service_requests_category] = #service_requests.category.name
#mail to:
end
end
and in send_service_email.html.erb/ send_service_email.txt.erb whatever suite in your case just call
<%= replace_dynamic_variables(#db_string,#variables)%>
I have not tested but hope this will work for you
I'm developing a web service (in Ruby) which needs to do a number of
different things for each message it receives.
Before my web service can process a message it must do different things:
sanitizing (e.g. remove HTML/JS)
check format (e.g. valid email provided?)
check IP in blacklist
invoke 3rd party web service
plus 10-30 other things
I'm thinking about implementing a filter/composite filter architecture
where each step/phase is a filter. For instance, I could have these filters
Sanitize input filter
Email filter
Country code filter
Blacklist filter
Each filter should be possible to reject a message, so I'm considering
that a filter should raise/throw exceptions.
This will give a lot of flexibility and hopefully a codebase that are
easy to understand.
How would you did this? And what are pros and cons of above design?
I would leave Exceptions for the cases when the filter itself actually broke down (e.g blacklist not available etc) and indicate the valid/invalid state either by true/false return values or, as you also suggested, throwing a tag.
If you don't want to stop at first failure, but execute all filters anyway, you should choose the boolean return type and conjunct them together (success &= next_filter(msg))
If I understood your situation correctly, the filter can both modify the message or check some other source for validity (e.g blacklist).
So I would do it like this:
module MessageFilters
EmailValidator = ->(msg) do
throw :failure unless msg.txt =~ /#/
end
HTMLSanitizer = ->(msg) do
# this filter only modifies message, doesn't throw anything
# msg.text.remove_all_html!
end
end
class Message
attr_accessor :filters
def initialize
#filters = []
end
def execute_filters!
begin
catch(:failure) do
filters.each{|f| f.call self}
true # if all filters pass, this is returned, else nil
end
rescue => e
# Handle filter errors
end
end
end
message = Message.new
message.filters << MessageFilters::EmailValidator
message.filters << MessageFilters::HTMLSanitizer
success = message.execute_filters! # returns either true or nil
I'm developing a Jenkins plugin in Ruby. You're supposed to be able to configure every node that connects to the server so that an email is sent to a specified address when the node loses its connection to the master. EmailNodeProperty adds a field to enter an email address:
#
# Save an email property for every node
#
class EmailNodeProperty < Jenkins::Slaves::NodeProperty
require 'java'
import 'hudson.util.FormValidation'
display_name "Email notification"
attr_accessor :email
def initialize(attrs = {})
#email = attrs['email']
end
def doCheckEmail value
puts " ENP.doCheckEmail:#{value}"
end
end
When you configure a node, there's a field named email where you can enter an email address. I want this field to be validated when you enter an address.
When you save the configuration, an EmailNodeProperty is created whence (that's right) you can access the email address.
MyComputerListener's offline gets called when a node loses its connection:
class MyComputerListener
include Jenkins::Slaves::ComputerListener
include Jenkins::Plugin::Proxy
def online(computer, listener)
end
def offline(computer)
#Do nothing when the Master shuts down
if computer.to_s.match('Master') == nil
list = computer.native.getNode().getNodeProperties()
proxy = list.find {"EmailNodeProperty"}
if proxy.is_a?(Jenkins::Plugin::Proxy)
rubyObject = proxy.getTarget()
email = rubyObject.email #<= Accesses the email from EmailNodeProperty
[...]
end
end
end
end
MyComputerListener finds the email address and sends an email.
Does anybody know if it is possible to validate the form in Ruby? According to the Jenkins wiki, this is what's supposed to be implemented (FIELD is supposed to be exchanged for the field name, so I guess it should be doCheckEmail):
public FormValidation doCheckFIELD(#QueryParameter String value) {
if(looksOk(value))
return FormValidation.ok();
else
return FormValidation.error("There's a problem here");
}
How would you do this in Ruby? Where should the method be implemented? In EmailNodeProperty or in MyComputerListener? How do you handle the QueryParameter? The # would make it an intstance variable in Ruby. (What is a Queryparameter?)
Any help would be much appreciated!
/Jonatan
This simply doesn't exist today, and we badly need to add it. This has been brought up a couple of times already in Thursday morning's hack session, so it's high on the TODO list. But as of ruby-runtime plugin 0.10, this just isn't possible. Sorry to let you down.