I am using a block method to print a list, but it is generating error.
class MyDataListBuilder
attr_accessor :object
def initialize(object)
#object = object
end
def column (&block)
content_tag :li, block.call
end
end
and using it as
<%= my_data_list_for #leads, [" :10", "Age:30", "Contact:140", "Phone:140", "Email:180", "Company:100", ""] do |l| %>
<%= l.column do %>
<%= object.age %>
<% end %>
<% end %>
other methods are
def list_headers(args=[])
args = Array.new(args)
columns = []
args.map { |o| columns << content_tag(:li, o.split(":").first, :style=>"width:#{o.split(":").second}px;") }
content_tag(:ul, columns.join(" ").html_safe, :class=>"list-headers")
end
def my_data_list_for(object, headers=[], &block)
arr = []
object.each do |o|
arr = capture(DataListHelper::MyDataListBuilder.new(o), &block)
end
content_tag(:ol, list_headers(headers) + arr, :class=>"data-list")
end
it is generating an error and i can not figure out why:
ActionView::Template::Error (undefined local variable or method `object' for #<#<Class:0xcaa1ca0>:0xca9ebf4>):
Please help me in it.
This solves the issue.
class MyDataListBuilder
include ActionView::Helpers::TagHelper
include ActionView::Helpers::CaptureHelper
attr_accessor :object, :output_buffer
def initialize(object)
#object = object
#output_buffer = nil
end
def column (&block)
if block_given?
content_tag(:li, capture(self, &block))
else
content_tag(:li, "")
end
end
end
Related
wrong number of arguments (given 2, expected 1)
SportsController
class SportsController < ApplicationController
def index
#sport = Sport.all
#events, #errors = Bapi::Inplay.all(query)
end
private
def query
params[:query, {}]
end
end
Sport index.html.erb
<% #sports.each do |sport| %>
<% #events(:sport_id => sport.id).each_slice(2) do |events| %>
I want send each sport.id to #enevts instance variable
Edited :
When send query as hash in SportsController its work!!
class SportsController < ApplicationController
def index
#sport = Sport.all
query = {:sport_id => 1}
#events, #errors = Bapi::Inplay.all(query)
end
private
def query
params[:query, {}]
end
end
Index.html.erb
<% #sports.each do |sport| %>
<% #events.each_slice(2) do |events| %>
params is a hash and method :[] can accept only 1 argument.
def query
params[:query] || {} # Will return :query part or empty Hash if it has nothing
end
I'm receiving results from a web service like this:
result.body returns:
[2] pry(#<User::EmailSettingsController>)> result.body
=> {"RESULT"=>
{"MESSAGES"=>
[{"MESSAGE"=>
{"TYPE"=>"E",
"ID"=>"HRRCF_WD_UI",
"NUMBER"=>"025",
"MESSAGE"=>"U kunt maximaal \"5\" jobagents creëren 1",
"LOG_NO"=>"",
"LOG_MSG_NO"=>"000000",
"MESSAGE_V1"=>"5",
"MESSAGE_V2"=>"1",
"MESSAGE_V3"=>"",
"MESSAGE_V4"=>"",
"PARAMETER"=>"",
"ROW"=>"0",
"FIELD"=>"",
"SYSTEM"=>""}},
{"MESSAGE"=>
{"TYPE"=>"E",
"ID"=>"HRRCF_WD_UI",
"NUMBER"=>"025",
"MESSAGE"=>"U kunt maximaal \"5\" jobagents creëren 2",
"LOG_NO"=>"",
"LOG_MSG_NO"=>"000000",
"MESSAGE_V1"=>"5",
"MESSAGE_V2"=>"2",
"MESSAGE_V3"=>"",
"MESSAGE_V4"=>"",
"PARAMETER"=>"",
"ROW"=>"0",
"FIELD"=>"",
"SYSTEM"=>""}},
{"MESSAGE"=>
{"TYPE"=>"E",
"ID"=>"HRRCF_WD_UI",
"NUMBER"=>"025",
"MESSAGE"=>"U kunt maximaal \"5\" jobagents creëren 3",
"LOG_NO"=>"",
"LOG_MSG_NO"=>"000000",
"MESSAGE_V1"=>"5",
"MESSAGE_V2"=>"3",
"MESSAGE_V3"=>"",
"MESSAGE_V4"=>"",
"PARAMETER"=>"",
"ROW"=>"0",
"FIELD"=>"",
"SYSTEM"=>""}}]}}
Is it possible to create something ParseMessageObject(result.body) that returns that I can do something like this.
message_list = ParseMessageObject(result.body)
message_list.each do |message|
puts message.message
puts message.type
end
I have no idea if this is possible or how to do this any suggestions to get me started are welcome!
EDIT 1:
Created my class in lib:
class MessageParser
def self.parse(result)
end
end
This should basically do what you want, using a simple open struct to create a message class which has accessors for each of the keys in your message hash
require 'ostruct'
class MessageParser
Message = Struct.new(:type, :id, :number, :message, :log_no, :log_msg_no, :message_v1, :message_v2, :message_v3, :message_v4, :parameter, :row, :field, :system)
attr_reader :messages
def initialize(data)
#data = data.fetch("MESSAGES",[])
#messages = []
parse_data
end
private
def parse_data
#data.each do | msg |
message = Message.new
msg.fetch("MESSAGE",{}).each do |key, value|
message[key.downcase.to_sym] = value
end
#messages << message
end
end
end
parser = MessageParser.new(result.body["RESULT"])
parser.messages.each do |message|
puts message.message
puts message.type
end
Something like this should work:
class ParsedMessages
include Enumerable
attr_reader :messages
def initialize(data)
#messages = extract_messages_from_data(data)
end
def extract_messages_from_data(data)
# TODO: Parse data and return message objects
end
def each &block
#messages.each do |message|
if block_given?
block.call message
else
yield message
end
end
end
end
Now you can use all methods from Enumerable on ParsedMessages, like each, find, map etc etc.
I need a helper that generates a link wrapped in a <li> including an active class.
Without supporting blocks this is easy:
def nav_item(*args, &block)
url = args[1]
clazz = 'active' if current_page?(url)
content_tag(:li, :class => clazz) do
link_to(*args)
end
end
But like link_to I want my helper to support blocks for defining content. With link_to I can do:
So how do I support the same in my helper?
All I need to do is pass the block through to link_to. My current attempt
def nav_item(*args, &block)
url = if block_given?
args.first
else
args[1]
end
clazz = 'active' if current_page?(url)
content_tag(:li, :class => clazz) do
if block_given?
# What goes here?
else
link_to(*args)
end
end
end
You can just pass the block to link_to as the last arg. Like this:
def nav_item(*args, &block)
url = if block_given?
args.first
else
args[1]
end
clazz = 'active' if current_page?(url)
content_tag(:li, :class => clazz) do
if block
link_to(*args, &block)
else
link_to(*args)
end
end
end
I have my custom presenter
class ShiftPresenter
def initialize(shift, template)
#shift = shift
#template = template
end
def h
#template
end
def users_list
logs = ShiftLog.by_shift(#shift)
names = logs.map do |log|
log.cardiologist.name
end
h.content_tag :div, names unless names.empty?
end
end
and #index view
- present shift do |shift_presenter|
= shift_presenter.user_list
How to present users names using li instead of ['tom', 'jerry']
You can add this to your presenter method:
def users_list
logs = ShiftLog.by_shift(#shift)
names = logs.map(&:cardiologist).map(&:name)#.compact.uniq # you can add this if you want
h.content_tag :div do
h.content_tag :ul do
ul_content = ''.html_safe
names.each do |name|
ul_content << h.content_tag :li, name
end
ul_content
end
end
The thing is it works as block with the return statement: the last used/returned object will be put inside the content_tag.
Try to wrap each element of names in users_list method into <li> tag and join them in a string. To do this you need to change this line:
h.content_tag :div, names unless names.empty?
into this:
h.content_tag :div, names.map{|str| '<li>' + str + '</li>'}.join unless names.empty?
I am trying to write a Rails helper method to convert a nested hash into a nested HTML list.
For example:
{
:parent => "foo",
:children => [
{
:parent => "bar",
:children => [
{
:parent => "baz",
:children => []
}
]
}
]
}
should become:
<ul>
<li>foo</li>
<ul>
<li>bar</li>
<ul>
<li>baz</li>
</ul>
</ul>
</ul>
The hash may have any number of levels, and any number of parents per level.
What is the best way to achieve this please?
You can make a recursive method to render to hash to a nested set of lists. Place this in your relevant helper:
def hash_list_tag(hash)
html = content_tag(:ul) {
ul_contents = ""
ul_contents << content_tag(:li, hash[:parent])
hash[:children].each do |child|
ul_contents << hash_list_tag(child)
end
ul_contents.html_safe
}.html_safe
end
Zach Kemp's answer very effectively addresses the question. If you are looking for something a bit more generic (a nested hash for which you will not know the key names), as I was, the following module may be helpful (also at https://github.com/sjohnson/auto_hash_display with more details):
module HashFormatHelper
# These methods add classes to the HTML structure that are defined in Bootstrap (and can be defined for other CSS frameworks)
def format_hash(hash, html = '')
hash.each do |key, value|
next if value.blank?
if value.is_a?(String) || value.is_a?(Numeric)
html += content_tag(:ul, class: 'list-group') {
ul_contents = ''
ul_contents << content_tag(:li, content_tag(:h3, key.to_s.underscore.humanize.titleize), class: 'list-group-item')
ul_contents << content_tag(:li, value, class: 'list-group-item')
ul_contents.html_safe
}
elsif value.is_a?(Hash)
html += content_tag(:ul, class: 'list-group') {
ul_contents = ''
ul_contents << content_tag(:li, content_tag(:h3, key.to_s.underscore.humanize.titleize), class: 'list-group-item')
inner = content_tag(:li, format_hash(value), class: 'list-group-item')
ul_contents << inner
ul_contents.html_safe
}
elsif value.is_a?(Array)
html += format_array(value)
else
Rails.logger.info "Unexpected value in format_hash: #{value.inspect}"
Rails.logger.info "value type: #{value.class.name}"
end
end
html.html_safe
end
def format_array(array, html = '')
array.each do |value|
if value.is_a?(String)
html += content_tag(:div, value).html_safe
elsif value.is_a?(Hash)
html += format_hash(value)
elsif value.is_a?(Array)
html += format_array(value)
else
Rails.logger.info "Unexpected value in format_array: #{value.inspect}"
Rails.logger.info "value type: #{value.class.name}"
end
end
html
end
end
This code can also be used to display XML by setting the hash value equal to Hash.from_xml(your_xml_data) and then passing that in to format_hash(hash).
Please note that the from_xml method may strip off XML tag attributes, so it works best for XML that doesn't have attributes.