Can you interpolate ruby variables within HAML css? - ruby-on-rails

I need a series of classes, .module1, .module2, ... module(n).
I also want to define those classes using css, ruby and HAML:
:css
.mod1 {
background-image: url("#{extra.image}");
}
Is it possible to interpolate ruby variables to save work?
.module.mod"#{extra.id}"
%h3 #{extra.title}
%p #{extra.description}
%a.btn-default{:href => "#", :target => "_top"} enter now
:css
.mod#{extra.id} {
background-image: url("#{extra.image}");
}

According to the HAML_REFERENCE I used this method:
- flavor = "raspberry"
#content
:textile
I *really* prefer _#{h flavor}_ jam.
to interpolate variables after :css
.module.modone{:class => "#{cycle("mod_#{extra.id}_")}"}
%h3 #{extra.title}
%p #{extra.description}
%a.btn-default{:href => "#", :target => "_top"} enter now
:css
.mod_#{extra.id}_ {
background-image: url("#{extra.image}");
background-color: #4073DF;
}

:css
.mod_#{extra.id}_ {
background-image: url("#{extra.image}");
height: #{ruby_height}#{measure_unit_ruby_variable};
}

Related

Leaflet Map Rails, Tiles Blank

Using the gem leaflet-rails
My initializer has the tile_layer and max_zoom
there is a height to the div: .mapid { height: 500px; }
Here is my html.erb
<% #imgData.each_with_index do |data, index| %>
<%=image_tag( data['images']["standard_resolution"]['url'] )%>
<div class="mapid" >
<%= map(:container_id => "map" + index.to_s, :center => {
:latlng => [data['location']['latitude'], data['location']['longitude']],
:zoom => 18
}) %>
</div>
When I hover on those links for the img src, they are valid and will lead me to a tile.
My tiles get loaded properly. There are no js errors, but nothing is being displayed... Any ideas?
You should give a height to the #map<nr> containers within that outer #mapid container, or you can do .leaflet-container { height:500px }.

ruby on rails qr code implemetation

hi just trying to create a qr code in my rails website using sam vincents qr code generator https://github.com/samvincent/rqrcode-rails3....... first i added this code to a controller
class QrcodeController < ApplicationController
def qrcode
respond_to do |format|
format.html
format.svg { render:qrcode => #qrurl, :level => :l, :unit => 10, :color => black }
format.png { render :qrcode => #qrurl }
format.gif { render :qrcode => #qrurl }
format.jpeg { render :qrcode => #qrurl }
end
end
def options
{:qrcode => "http://helloworld.com", size => 4}
end
end
then i am not sure what to add in the view i tried this
<div class="Qrcode qr">
<h2>Qr code</h2>
<p><%= link_to "SVG", Qrcode_path("svg") %></p>
<p><%= link_to "PNG", Qrcode_path("png") %></p>
<p><%= link_to "JPEG", Qrcode_path("jpeg") %></p>
<p><%= link_to "GIF", Qrcode_path("gif") %></p>
would appreciate any help on how it works as their are not that many instructions online
im using ruby 1.9.3 and rails 4.0.1
I'm using rqrcode gem. It's pretty simple and you don't need to generate images for your qrcodes. The code is generated using tables and some css styles...
You can use this helper: /helpers/qrcode_helper.rb
module QrcodeHelper
require 'rqrcode'
def render_qr_code text, size = 3
return if text.to_s.empty?
qr = RQRCode::QRCode.new(text)
sizeStyle = "width: #{size}px; height: #{size}px;"
content_tag :table, class: "qrcode pull-right" do
qr.modules.each_index do |x|
concat(content_tag(:tr) do
qr.modules.each_index do |y|
color = qr.dark?(x, y) ? 'black' : 'white'
concat content_tag(:td, nil, class: color, style: sizeStyle)
end
end)
end
end
end
end
Into your view some_view.html.erb
<%= render_qr_code("MYCODE") %>
And you need to add style for your code qrcode.css.less
table.qrcode {
border-width: 0;
border-style: none;
border-color: #0000ff;
border-collapse: collapse;
margin-top: 100px;
margin-bottom: 12px;
td {
border-width: 0;
border-style: none;
border-color: #0000ff;
border-collapse: collapse;
padding: 0;
margin: 0;
width: 3px;
height: 3px;
&.black {
background-color: #000 !important
}
&.white {
background-color: #fff !important
}
}
}
My example it's working with Rails 3.
Here's a minimal example that avoids the need to write code to render each (x,y) "pixel" yourself.
In your controller:
def show
#qr = RQRCode::QRCode.new('https://stackoverflow.com/')
end
And then in your corresponding .html.erb view:
<p>
<%== #qr.as_svg %>
</p>
(Note that this uses <%==, not <%=; if you use the latter, you'll get the raw SVG XML source instead of a rendered SVG image.)
See the RQRCode docs for options that can be passed to .as_svg, and for other output options such as PNG.

Rails link_to with turbolinks and the new hash style

this works nicely
= link_to 'All', test_path(:param1 => xxx), 'data-no-turbolink' => true
and translates to
<a data-no-turbolink="true" href="/test?param1=xxx">All</a>
I want to change it to the new hash syntax so I did this:
= link_to 'All', test_path(param1: xxx), data: { no: { turbolink: true }}
but it translates to
<a data-no="{"turbolink":true}" href="/test?param1=xxx">All</a>
EDIT: This Works:
%a{href: "#{test_path(param1: xxx}", data: { no: { turbolink: true }}} All
which translates to
<a data-no-turbolink href='/test?param1=xxx'>All</a>
but shouldn't I stick to link_to rather than <a href></a>?
There are some naming conventions, so you must write like this:
link_to 'All', test_path(param1: xxx), data: {no_turbolink: true}
You should always try to use the rails helper methods when they're available. This way you'll get all the benefits of rails: cache-busting and relative pathing and whatever else comes in the future. Given that, the issue in your code is that the data hash can only be one level deep. So do this instead:
= link_to 'All', test_path(param1: xxx), data: { 'no-turbolink' => true }
Note: You can't really use a symbol for the no-turbolink part because symbols don't interpret hyphens. https://gist.github.com/misfo/1072693

undefined method `error_message_on' after implementing simple private messages [duplicate]

I have a form with input fields/labels etc. How do I get the error message to show up next to the field? instead of clumped together at the top?
I am using devise, rails 3
I have this at the top of my form:
= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
- if resource.errors.any?
#errorExplanation
%h2
= pluralize(resource.errors.count, "error")
prevented this user from being saved:
%ul
- resource.errors.full_messages.each do |msg|
%li
= msg
You can use this
- if #resource.errors[:field_name]
...
Also useful link:
http://guides.rubyonrails.org/active_record_validations.html#working-with-validation-errors
Just create a file in your initializers folder.
config/initializers/inline_errors.rb
Place this code in it:
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
unless html_tag =~ /^<label/
%{<div class="has-error">#{html_tag}<span class="help-block">#{instance.error_message.first}</span></div>}.html_safe
else
%{#{html_tag}}.html_safe
end
end
PD: Sorry for my english.
How about this
if you want to put the error message just beneath the text field, you can do like this
.row.spacer20top
.col-sm-6.form-group
= f.label :first_name, "*Your First Name:"
= f.text_field :first_name, :required => true, class: "form-control"
= f.error_message_for(:first_name)
What is error_message_for?
--> Well, this is a beautiful hack to do some cool stuff
# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
def error_message_for(field_name)
if self.object.errors[field_name].present?
model_name = self.object.class.name.downcase
id_of_element = "error_#{model_name}_#{field_name}"
target_elem_id = "#{model_name}_#{field_name}"
class_name = 'signup-error alert alert-danger'
error_declaration_class = 'has-signup-error'
"<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
"#{self.object.errors[field_name].join(', ')}"\
"</div>"\
"<!-- Later JavaScript to add class to the parent element -->"\
"<script>"\
"document.onreadystatechange = function(){"\
"$('##{id_of_element}').parent()"\
".addClass('#{error_declaration_class}');"\
"}"\
"</script>".html_safe
end
rescue
nil
end
end
Result
Markup Generated after error
<div id="error_user_first_name" for="user_first_name" class="signup-error alert alert-danger">This field is required.</div>
<script>document.onreadystatechange = function(){$('#error_user_first_name').parent().addClass('has-signup-error');}</script>
Corresponding SCSS
.has-signup-error{
.signup-error{
background: transparent;
color: $brand-danger;
border: none;
}
input, select{
background-color: $bg-danger;
border-color: $brand-danger;
color: $gray-base;
font-weight: 500;
}
&.checkbox{
label{
&:before{
background-color: $bg-danger;
border-color: $brand-danger;
}
}
}
Note: Bootstrap variables used here
and, do not forget to Restart the server now and after any modification to the file in config dir.
You can use error_message_on
http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_message_on
Update:
form.error_messages was removed from Rails and is now available as a plugin. Please install it with rails plugin install git://github.com/rails/dynamic_form.git.
If anyone is looking for a way how to display error messages for particular field in Rails 6:
a = Post.new
a.save # => false
a.errors.full_messages_for(:title)
["Title can't be blank"]
a.errors.full_messages_for(:title).join(', ')
"Title can't be blank, Title too short"

How can I iterate through a CSS class' subclasses?

I have a CSS file which contains several hundred 16x16 icons. They are referenced using a CSS class/subclass arrangement, like so:
<span class="icons icon_name"></span>
So, if I need an "arrow up" icon, I simply code:
<span class="icons arrow_up"></span>
And so on. Because there are so many icons in the library, I created a reference page (in Haml), so I could quickly find which icon I need. An example of the Haml code:
%div.icons.arrow_turn_right
arrow_turn_right
%br
%div.icons.arrow_undo
arrow_undo
%br
%div.icons.arrow_up
ss_arrow_up
%br
It occurs to me that this is a rather brute force method to writing the page. 300 icons require nearly 1000 lines of code.
My question: Is there a way to iterate through a CSS class' subclasses using an each loop (or something similar)?
Something like this:
subs = mainCSSclass.allSubclasses <--Replace this line with functional code
subs.each do |subclass|
... display the |subclass| ...
end
Is such a thing possible?
Edit: Here is a partial of the actual CSS file being referenced:
.icons {
display: inline;
overflow: hidden;
height: 16px;
padding-left: 18px;
background: url(icons.png) no-repeat;
}
.accept {
background-position: 0px 0px;
}
.add {
background-position: 0px -19px;
}
.anchor {
background-position: 0px -37px;
}
.application {
background-position: 0px -55px;
}
.application_add {
background-position: 0px -73px;
}
.application_cascade {
background-position: 0px -91px;
}
Solution (thanks to #Corroded's answer):
In my pages_helper.rb:
def read_css_cfg
css_classes = Array.new
file = File.new("public/stylesheets/blueprint/plugins/icons/icons.css", "r")
while line = file.gets
parsed = line.scan(/[.]\w+ {/).to_s.scan(/\w/).join
css_classes << parsed if !parsed.blank?
end
file.close
css_classes
end
In my actual Haml file:
- parse = read_css_cfg
- parse.delete("icons") #unrelated class, but in the same file'
- column = 1
.container
- parse.each do |class_name|
- case column
- when 1
<div class = "css_row">
%div{:class => "icons #{class_name} three_column"}
#{class_name}
- column += 1
- when 2
%div{:class => "icons #{class_name} three_column"}
#{class_name}
- column += 1
- when 3
%div{:class => "icons #{class_name} three_column"}
#{class_name}
</div>
- column = 1
Finally, though this has nothing to do with the original question, my final answer contained code which auto-generated a 3-column "div-table." If you're interested in the CSS to use DIV's instead of a table, here it is:
.container {
display: table;
width: 675px;
}
.three_column {
display: table-cell;
width: 225px;
}
.css_row {
display: table-row;
Okay, so basically, the plan is to loop through all those classes and generate them in a Haml page, right?
What I would do is open that CSS file (using Ruby of course) and then use a regular expression to parse and get all the subclasses. Since you would want to call that in a view, then I suggest using a helper:
def loadCSSClasses
cssClasses = []
cssFile = File.open("yourcssfile.css") do
#Forgive me, my regular expression is weak, but basically you would want to get all the classnames after the word ".icon."
cssClasses << className
end
cssClasses
end
Then in your Haml file do this:
%ul
- loadCSSClasses.each do |class_name|
%li{:class => "icon #{class_name}"
= "ss_#{class_name}"

Resources