How can I get Title & href (URL)? - ruby-on-rails

I have following HTML code. I want to get the href & title of the product & store them into different variables. I have tried following code.
within("div.product-action") do
#product_url = find("a.href")
end
But that throws an error.
Capybara::ElementNotFound: Unable to find css "a.href"
My HTML code is as follow:
<div class="product-action zoom" ng-class="{ 'logged-out': !user.$isLoggedIn }">
<a href="/g/women/christian-dior/so-real-sunglasses-colorless" title="Christian Dior So Real" Sunglasses-Colorless" ng-click="ProductUtils.cache(result)" class="bottom-action-container quickview-button hover-option" track="{
type: 'product-info',
name: moduleType,
breadcrumbs: result.breadcrumbs || breadcrumbs
}">
<i class="icon-zoom"></i>
</a>
</div>

a.href will select the a elements that have a href class. This is not what you want.
You can access the attributes as a hash after you found the element:
a = find('.product-action a')
href = a[:href]
title = a[:title]

You can find the href and title of given html code with below mentioned code:
within("div.product-action") do
productUrl = find(:css, '.bottom-action-container')[:href]
productTitle = find(:css, '.bottom-action-container')[:title]
end
OR
within("div.product-action") do
productUrl = find('a')[:href]
productTitle = find('a')[:title]
end
Hope this helps :)

Related

Ruby/Rails button and search filtering

I've added the Active and Archived buttons to this page for extra filtering.
The existing search box functionality uses the following js.coffee which calls the controller index to pull the data from the db.
triggerSearch: (e) ->
if searchCompanyTimer
window.clearTimeout searchCompanyTimer
searchCompanyTimer = window.setTimeout(( ->
searchCompanyTimer = null
query_text = $(e.currentTarget).val()
el_id = $(e.currentTarget)[0].id
$.get( "companies", "q[name_cont]": query_text )
), 500, e)
I have added 2 similar js.coffee methods which set an active flag to true or false depending on which button was pressed.
Here is one of those methods.
triggerShowActive: (e) ->
if searchCompanyTimer
window.clearTimeout searchCompanyTimer
searchCompanyTimer = window.setTimeout(( ->
searchCompanyTimer = null
$.get( '/companies', {active: true} )
), 500, e)
here is part of my controller.
class CompaniesController < ApplicationController
respond_to :js, :json, :html
$active_inactive_flag = true
def index
puts "params are: #{params}"
puts "active param is: #{params[:active]}"
puts "#active_inactive_flag pre any conditions is: #{$active_inactive_flag}"
$active_inactive_flag = params[:active] ? params[:active] : $active_inactive_flag
puts "#active_inactive_flag after check on params[:active] is: #{$active_inactive_flag}"
if $active_inactive_flag.try :nonzero?
$active_inactive_flag = true
end
puts "#active_inactive_flag after check if it has a value, else true - is: #{$active_inactive_flag}"
#companies =
Company.search(params[:q])
.result
.order('created_at DESC')
.page(params[:page])
.per(Settings.paginate_limit)
.where(is_active: $active_inactive_flag)
end
here is my index.html.erb file where the buttons and search code is.
<div class="row">
<div class="col-md-3">
<label>Filter By:</label>
<button class="show_active btn btn-primary" style="border-radius:10px">Active</button>
<button class="show_inactive btn btn-primary" style="border-radius:10px">Archived </button>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">Filter by name</span>
<input class="form-control" id="q_name_cont" name="q[name_cont]" type="text">
</div>
</div>
</div>
I am using a global variable (tried instance and class variables also) in the controller but it's not working as expected. Sometimes the value in $active_inactive_flag switches from false to true or vice versa incorrectly. I don't want to use a global variable but I am at a loss as to how to combine both filter and search correctly. When the page loads we want Active button to be on by default and return active companies. The problem I am having is knowing what button was pressed when the search box is used.
Edit:
Here is an example of what is happening.
Any direction would be grateful.
Thanks Dave,
in js.coffee added the following:
returnActiveInctiveFlag = true
and then to the triggerSearch updated to:
$.get( "companies", { "q[name_cont]": query_text, active: returnActiveInctiveFlag } )
In my new methods updated returnActiveInctiveFlag accordingly.
Was really overcomplicating it. Thanks again for getting me thinking in the correct way.

Rails fullname method, wrap in spans

I have a simple method on a Person model like so:
def fullname
[title, forenames, surname].join(" ")
end
Sometimes, the output I get from this is perfect, othertimes I need each part wrapped in a span with a class. I could do this in the method but it sort of feels wrong to be putting spans in the model.
Can anyone offer a nicer solution? How would you get this method to offer both of the following output options:
Title Forenames Surname
<span class"title">Title <span class"forenames">Forenames <span class"surname">Surname
Thanks
Try this:
def fullname(spanned = false)
{
'title': title,
'forenames': forenames,
'surname': surname
}.map { |k,v| spanned ? "<span class='#{k}'>#{v}</span>" : v }.join(' ')
end
puts(fullname(true))
# result: <span class='title'>title</span> <span class='forenames'>forenames</span> <span class='surname'>surname</span>
puts(fullname)
# result: title forenames surname

How to save using the Mercury editor

I want to get the save function in the Mercury editor working but to no avail.
I have a model to save the page, title and content.
mercury.js:
$(window).bind('mercury:ready', function() {
var link = $('#mercury_iframe').contents().find('#edit_link');
Mercury.saveURL = link.data('save-url');
link.hide();
});
$(window).bind('mercury:saved', function() {
window.location = window.location.href.replace(/\/editor\//i, '/');
});
static_pages_controller.rb:
def update
#static_page = StaticPage.find(params[:id])
#static_page.page = params[:page]
#static_page.title = params[:content][:aboutContainer][:value][:about_title][:value]
#static_page.content = params[:content][:aboutContainer][:value][:about_content][:value]
#static_page.save!
render plain: ''
end
about.html.erb:
<% provide(:title, 'About') %>
<div class="container" id="aboutContainer" data-mercury="full">
<h1 id="about_title"><%= raw #static_page.title %></h1>
<div class="col-sm-12">
<p id="description about_content"><%= raw #static_page.content %></p>
</div>
<p><%= link_to "Edit Page", "/editor" + request.path, id: "edit_link",
data: {save_url: static_page_update_path(#static_page)} %></p>
</div>
Ok, so i basically realised that I needed a show action so I can grab records from the model and save to the #static_page object
I was following this guide: http://railscasts.com/episodes/296-mercury-editor?autoplay=true
Please note I had to change my routes to using those in the link (or similar routes to them) and had to place them before the default mercury routes and had to change:
#static_page.title = params[:content][:aboutContainer][:value][:about_title][:value]
#static_page.content = params[:content][:aboutContainer][:value][:about_content][:value]
to:
#static_page.title = params[:content][:about_title][:value]
#static_page.content = params[:content][:about_content][:value]
I then removed the class 'container' div in about.html.erb and moved all the code to show.html.erb not needing about.html.erb.

Convert string with HTML tags in ASP.NET MVC

Is there a way to pass a string with HTML tags without changing the Razor code?
Scenario (current code):
string msg = "<a href='http://www.google.com/html/'>Google</a>";
OUTPUT:
<a href='http://www.google.com/html/'>Google</a> on the page.
GOAL result:
Link to Google without changing the code "#msg".
try #Html.Raw(HttpUtility.HtmlDecode(msg));
You can try with
HtmlString msg = new HtmlString("<a href='http://www.google.com/html/'>Google</a>");
instead of
string msg = "<a href='http://www.google.com/html/'>Google</a>";
Hey You can edit your razor code as:
#{
HtmlString msg = new HtmlString("Hello <br> Hello Again");
<p style="text-align:justify;"> #msg </p>
}
It's simple

Html.LabelFor labelText with HTML

Currently it's returning the HTML as a string. Is there an easy way to get this to properly output HTML?
#Html.LabelFor(m => m.DisplayName,
Html.Raw(Html.Partial("_Tooltip", new Tooltip {
Title = Model.DisplayName,
Description = "This is my test description"}
).ToString())
.ToString())
How about using regular HTML?
<label for="DisplayName">
#Html.Partial("_Tooltip", new Tooltip { Title = Model.DisplayName, Description = "This is my test description" }
</label>
The problem you're running into is that the LabelFor helper automatically HTML-escapes the label, assuming that you're passing it just a regular string that shouldn't have HTML in it.
I was able to solve this by creating an extension method for it, following this example: http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx
With the exception that I updated this:
tagBuilder.SetInnerText(innerText);
To this:
tagBuilder.InnerHtml = innerText;
If you do not want the raw html, remove the Html.Raw() function as follows:
#Html.LabelFor(m => m.DisplayName, Html.Partial("_Tooltip", new Tooltip { Title = Model.DisplayName, Description = "This is my test description" }).ToString().ToString())

Resources