Helper methods available in mailer views depend on environment? - ruby-on-rails-3

Related to my previous question I still have one thing that I would like to understand - why this:
= link_to(root_path)
= link_to(#some_path_set_in_mailer)
works in development mode (config.action_mailer.perform_deliveries was set to true and emails were actually sent) and in production or staging has to be changed to:
= link_to(#some_path_set_in_mailer, #some_path_set_in_mailer)
to avoid "No route matches {}" error?
I had this problem in rails 3.2.

I'm not entirely sure why there is a difference since there shouldn't be.
However, link_to typically has this format:
= link_to("Some link description here", root_path)
The only time you typically leave off the link description text is if you have a longer description that you need to put within a do block like this:
= link_to(root_path) do
%p Some link description here
= image_tag("some_image.jpg")
So I would recommend sticking to the preferred syntaxes above.
The docs for link_to don't really talk about the short-hand method you're using too much.
Here is the source for it:
# File actionpack/lib/action_view/helpers/url_helper.rb, line 231
def link_to(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
link_to(capture(&block), options, html_options)
else
name = args[0]
# this is probably where your issue is coming from
options = args[1] || {}
html_options = args[2]
html_options = convert_options_to_data_attributes(options, html_options)
url = url_for(options)
href = html_options['href']
tag_options = tag_options(html_options)
href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
"<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
end
end

Related

If then else implementation to chose baseURL in Karate DSL

I have a little tricky requirement in Karate. I have a set of baseURL's in my karate.config which are chosen based on the implementation. Here is the snippet of it:
if (env == 'qa') {
config.apiKey = apiKey;
config.tsp_api = 'https://api.qa.tceu.net';
config.svt_dcm = 'https://svt.qa.tceu.net';
config.acn_dcm = 'https://acn.qa.tceu.net';
config.sos_dcm = 'https://sos.qa.tceu.net';
config.cust_dcm = 'https://cust.qa.tceu.net';
Here tsp,svt,acn,sos,cust are some actions.
I have a feature file which passes the action as a parameter:
# Vehicle Initiates the action
When def Perform_Report_Notification = call read('./../common/performActionNotification.feature') { action: '#(action)' }
In the called performActionNotification.feature, I need to pick up the url from the karate.config file based on the action that is passed. For example if the action is sos, then the url should be sos_dcm. If the action is svt then the url should be svt_dcm
Here is the snippet from performActionNotification.feature and what I am currently doing for sos:
Given url sos_dcm
And path '/AU/v1.0/TSP/'+ action
And request RequestPayload
When method post
Then status 200
I want to implement something like an if then else similar to:
if (action == 'sos')
then myurl == 'sos_dcm'
else if (action == 'acn')
then myurl == 'acn_dcm'
else if (action == 'svt')
then myurl == 'svt_dcm'
Given url myurl
And...
And...
...
I tried a sort of a hack and it works but its not a clean way of doing it. Instead of reading the URL from karate.config I am hardcoding it this way:
Given url 'https://'+act+'.qa.tceu.net'
One more thing I tried was
* def myurl = action +'_dcm' #so if action is acn then the variable myurl would be acn_dcm
Given url myurl
...
....
But this hardcodes the url as 'acn_dcm' instead of picking the defined url up from karate.config.
Can someone kindly suggest the best way to implement this?
Here is a hint. JSON is actually a pretty useful data-structure (think hash-map or dictionary) and you can lookup a value without needing an if statement.
* def data =
"""
{
qa: {
sos: 'https://sos.qa.tceu.net',
acn: 'https://acn.qa.tceu.net'
}
}
"""
* def env = 'qa'
* def urls = data[env]
* def action = 'sos'
* def actionUrl = urls[action]
* match actionUrl == 'https://sos.qa.tceu.net'
This should get you on your way :)
EDIT - also see this: https://stackoverflow.com/a/67868935/143475
I've finally used Peter's most elegant solution and it works like a charm!
Here's what I've finally implemented that does not need hardcoding of the endpoint URL's and is driven by endpoints in the karate.config file.
* def data =
"""
{
qa: {
sos: '#(sos_dcm)', # sos_dcm endpoint defined in karate.config file
acn: '#(acn_dcm)',
svt: '#(svt_dcm)'
}
}
"""
* def env = karate.properties['env']; # Driven by maven commandline arg -Denv=qa as an example
* def urls = data[env]
* def action = act # act comes from the calling feature file and has values - sos/acn/svt
* def myUrl = urls[action]
Given url myUrl
...
...
I would suggest looking into using javascript for your conditional logic
So the javascript function takes a param of action and then the if and else statements returns the variable of the url that you need.
Perform the javascript function before you make the request call. and use the variable that is returned by js to determine the logic.
make that js file a common function that can be accessed by multiple feature files.
function determineUrl(action) {
var url = "${urDefaultUrl}";
if (action == "sos") url == "${full url}";
else if (action == "acn") url == "${full url}";
return url;
}
Then in your feature file
* def urlDecider = 'classpath to your js function'
* myUrl = urlDecider(action)
* url myUrl
* Given path ....
For the sake of the community learning, there is one other way I figured out on similar lines of Jawad's solution is using a Java function. They do exactly the same thing as Jawad's solution but just that its a java class doing it. If a project has java class files, then to maintain consistency this solution can be used too.
Here is the how the class file looks:
public class DCMUrlDecider {
static String dcmURL="";
public static String getDCMUrl(String action) {
if (action.matches("sos"))
{
dcmURL = "https://sos.qa.tceu.net";
}
else if (action.matches("acn"))
{
dcmURL = "https://acn.qa.tceu.net";
}
else if (action.matches("svt"))
{
dcmURL = "https://svt.qa.tceu.net";
}
return dcmURL;
}
}
And here is the associated code snippet from the feature file:
* def dcmURLDecider = Java.type('com.TCEU.KarateTests.DCMUrlDecider')
* def myUrl = dcmURLDecider.getDCMUrl(act)
Given url myUrl
....
.....
Once again this means we are still hardcoding URLs in the java class files. Need to learn a way of doing it via karate.config files if possible.

Needs redirects for routing

I'm very excited about Camaleon cms for rails 5; however, I've noticed a significant problem with posts that have parent slugs or have post-type slugs in the url as a url format.
For background, it's very important that a post's content can only be reached via one single url. Otherwise, you have the potential for getting penalized in google for having duplicate content. For those who rely on search engine traffic (basically everyone who would ever use a CMS), this is a very serious issue.
The following is an example of the issue. All of these urls will render the same post content:
http://www.example.com/parent_slug/post_slug
http://www.example.com/post_slug
http://www.example.com/parent_slug_blah_blah/post_slug
Or
http://www.example.com/post_type/post_slug
http://www.example.com/post_slug
http://www.example.com/post_type_blah_blah/post_slug
The way Wordpress deals with this issue is to redirect to the proper url with the correct parent slug if it doesn't exist or if it is misspelled.
My question here is for those in the know, is this perhaps a priority issue in one of the upcoming releases?
I'm not sure if this will work for everyone, but here's my solution to this issue.
Requirements: this will only work for posts that have the "post_of_posttype", "heirarchy_post" or "post_of_category_post_type" route formats.
The following code is extending the functionality of Camaleon's frontend controller method render_post by simply adding a redirect when the params don't match the #post.the_path. Seems to work for my purposes. Hopefully it will help someone else.
Create a new file in your config/initializers folder and place the following code:
# config/initializers/camaleon_custom_post.rb
CamaleonCms::FrontendController.class_eval do
# render a post
# post_or_slug_or_id: slug_post | id post | post object
# from_url: true/false => true (true, permit eval hooks "on_render_post")
def render_post(post_or_slug_or_id, from_url = false, status = nil)
if post_or_slug_or_id.is_a?(String) # slug
#post = current_site.the_posts.find_by_slug(post_or_slug_or_id)
elsif post_or_slug_or_id.is_a?(Integer) # id
#post = current_site.the_posts.where(id: post_or_slug_or_id).first
else # model
#post = post_or_slug_or_id
end
unless #post.present?
if params[:format] == 'html' || !params[:format].present?
page_not_found()
else
head 404
end
else
#post = #post.decorate
if ["post_of_posttype","hierarchy_post"].include? #post.the_post_type.contents_route_format
if params[:parent_title].nil? && params[:post_type_title].nil?
params_path = "/" + params[:slug]
elsif !params[:parent_title].nil?
params_path = "/" + params[:parent_title] + "/" + params[:slug]
elsif !params[:post_type_title].nil?
params_path = "/" + params[:post_type_title] + "/" + params[:slug]
end
unless (#post.the_path === params_path)
redirect_to #post.the_url, status: 301 and return
end
elsif #post.the_post_type.contents_route_format === "post_of_category_post_type"
if [params[:post_type_title],params[:label_cat],params[:category_id],params[:title]].all?
params_path = [params[:post_type_title],params[:label_cat],params[:category_id] + "-" + params[:title],params[:slug]].join("/")
params_path.prepend("/")
unless (#post.the_path === params_path)
redirect_to #post.the_url, status: 301 and return
end
else
redirect_to #post.the_url, status: 301 and return
end
end
#object = #post
#cama_visited_post = #post
#post_type = #post.the_post_type
#comments = #post.the_comments
#categories = #post.the_categories
#post.increment_visits!
# todo: can_visit? if not redirect home page
home_page = #_site_options[:home_page] rescue nil
if lookup_context.template_exists?("page_#{#post.id}")
r_file = "page_#{#post.id}"
elsif #post.get_template(#post_type).present? && lookup_context.template_exists?(#post.get_template(#post_type))
r_file = #post.get_template(#post_type)
elsif home_page.present? && #post.id.to_s == home_page
r_file = "index"
elsif lookup_context.template_exists?("post_types/#{#post_type.the_slug}/single")
r_file = "post_types/#{#post_type.the_slug}/single"
elsif lookup_context.template_exists?("#{#post_type.slug}")
r_file = "#{#post_type.slug}"
else
r_file = "single"
end
layout_ = nil
meta_layout = #post.get_layout(#post_type)
layout_ = meta_layout if meta_layout.present? && lookup_context.template_exists?("layouts/#{meta_layout}")
r = {post: #post, post_type: #post_type, layout: layout_, render: r_file}
hooks_run("on_render_post", r) if from_url
if status.present?
render r[:render], (!r[:layout].nil? ? {layout: r[:layout], status: status} : {status: status})
else
render r[:render], (!r[:layout].nil? ? {layout: r[:layout]} : {})
end
end
end
end
Seems kind of strange the mandatory redirect for non-accurate urls is not in the core camaleon application, but perhaps most people who use this cms are creating internally facing apps. Anyway, if that's not the case, I think this should be a priority fix.

Rails 3: accept all params except a specific value

I have a Rails 3.2.13 Application to maintenance.
Because of authorization rules i want to limit the find(params[:file_registry_id]) method to accept all parameters except 752. (Only user tehen should be able to get it.)
def show
if current_user.tehen?
#file_registry = FileRegistry.find(752)
else
#file_registry = FileRegistry.find(params[:file_registry_id])
end
#rubric = Rubric.find(params[:id])
#rubrics = expanded_rubrics #rubric.ancestors_with_self.collect(&:id)
set_favorites
render :action => 'index'
end
Is there a method available to filter an element (here id 752) from the params hash? Or what's the best way to go?
Simple solution:
def show
#file_registry = get_file_registry
#....
end
private
def get_file_registry
if current_user.tehen?
FileRegistry.find(752)
else
unless params[:file_registry_id] == FORBIDDEN_ID_FOR_GUEST
FileRegistry.find(params[:file_registry_id])
else
false
end
end
end
FORBIDDEN_ID_FOR_GUEST should be defined outside of the controller, for example inside of a initializer.
But I suggest to use a authorization library like CanCan (https://github.com/ryanb/cancan) where you can define permissions for every use case.

Custom error message processor without monkey patch

I've implemented a custom error message processor for Korean language. In Korean, postpositions take different forms depending on the sound of the preceding noun or pronoun.
For example, when marking a subject, ka (가) is used following a vowel and i (이) is used following a consonant.
Examples (hyphens are to denote morpheme boundaries):
Romanization: sakwa-ka ppalkah-ta.
Gloss: Apple-SUBJECT red-PRESENT.
Translation: Apple is red.
Romanization: phainayphul-i tal-ta.
Gloss: Pineapple-SUBJECT sweet-PRESENT.
Translation: Pineapple is sweet.
Therefore, the standard error message system implemented in ActiveModel::Errors is not adequate for Korean. You should either include the attribute in the message making a lot of duplicates ("A is blank", "B is blank", "C is blank", ...), or avoid postpositions after the attribute which is often difficult or makes awkward sentences.
I monkey patched ActiveModel::Errors and altered generate_message to solve this problem. Following is the code (Gist) which is currently in config/initializers in my Rails app.
# encoding: UTF-8
# Original article: http://dailyupgrade.me/post/6806676778/rubyonrails-full-messages-for-korean
# Modified to support more postpositions and client_side_validations gem.
#
# Add Korean translations like this:
# ko:
# errors:
# format: "%{message}"
# messages:
# blank: "%{attribute}((이)) 입력되지 않았습니다"
# taken: "이미 사용 중인 %{attribute}입니다"
# invalid: "잘못된 %{attribute}입니다"
# too_short: "%{attribute}((이)) 너무 짧습니다"
#
class Korean
POSTPOSITIONS = {"은" => "는", "이" => "가", "을" => "를", "과" => "와", "으로" => "로"}
def self.select_postposition(last_letter, postposition)
return postposition unless last_letter >= "가" && last_letter <= "힣"
final = last_letter.mb_chars.last.decompose[2]
if final.nil?
# 받침 없음
POSTPOSITIONS[postposition] || postposition
elsif final == "ㄹ" && (postposition == "으로" || postposition == "로")
# 'ㄹ 받침 + (으)로'를 위한 특별 규칙
"로"
else
# 받침 있음
POSTPOSITIONS.invert[postposition] || postposition
end
end
end
module ActiveModel
class Errors
old_generate_message = instance_method("generate_message")
define_method("generate_message") do |attribute, type = :invalid, options = {}|
msg = old_generate_message.bind(self).(attribute, type, options)
return msg unless I18n.locale == :ko
msg.gsub(/(?<=(.{1}))\(\((은|는|이|가|을|를|과|와|으로|로)\)\)/) do
Korean.select_postposition $1, $2
end
end
end
end
My first question is whether it is possible to achieve the same goal without monkey patching. I'm new to Rails (and Ruby too) so couldn't come up with a better solution.
The second question is about extracting this code from my Rails app and making it into a separate gem. I'm cutting my teeth on developing gems and recently made my first gem. In what place should I put this code in a gem? config/initializers doesn't seem right.
I'm not good at ruby but the following javascript code do the same thing. I hope it may help.
var hasJongsung = function(word) {
return !!(word && word[word.length -1].charCodeAt()>=0xAC00 && word[word.length-1].charCodeAt()<=0xD7A3 && (word[word.length -1].charCodeAt()-0xAC00)%28);
};
source:http://spectrumdig.blogspot.kr/2012/11/unicode-20.html

Alter URL using ActiveResource

I am using ActiveResource to manage accessing an external service.
The external service has an URL like:
http://api.cars.com/v1/cars/car_id/range/range_num?filter=filter1,filter2
Here's my Car class:
class Car < ActiveResource::Base
class << self
def element_path(id, prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"
end
def collection_path(prefix_options = {}, query_options = nil)
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
end end
self.site = "http://api.cars.com/"
self.prefix = "/v1/"
self.format = :json
end
When I set up my object to get a particular car in rails console:
> car = car.new
> car.get('1234')
I get a URL like this:
http://api.cars.com/v1/cars//1234.json
How do I get the URL to include the range and range_num elements?
Also, i don't want the .json extension on the end of the URL. I've attempted overriding the element_name and collection_name methods as described here: How to remove .xml and .json from url when using active resource but it doesn't seem to be working for me...
Thanks in advance for any ideas!
Get rid of the forward slash in the URL
"#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"
becomes:
"#{prefix(prefix_options)}#{collection_name}#{URI.parser.escape id.to_s}#{query_string(query_options)}"