Grails - Set "disabled" attribute name and value in GSP - grails

I´m trying to do this without success:
<g:textField title="${title}" ${disabled} />
I want to apply a disabled attribute, ONLY if the ${disabled} variable is TRUE.
I don't want to use conditionals, because in other views I got a lot of code and using IF statements, will be a chaos.
The other thing is applying the attribute like this:
<g:textField title="${title}" disabled="${disabled}" />
But when I put the disabled attribute, no mather the content of the variable, It just always disables the field.

if you don't like gotomanners' solution (which seems perfectly valid to me)
<g:textField title="${title}" ${(disabled)?"disabled":""} />

your ${disabled} variable should be returning "disabled" not TRUE for that to work.
EDIT
I tried this out and saw the problem with it always being disabled no matter the value. Apparently the mere presence of the disabled keyword disables the field and the value assigned to that keyword is only a dummy value.
Anyway, Here's a fix.
Create a Taglib class(if you don't have one already)
define your own textfield tag as such...
def myTextField = { attrs, body ->
def title = attrs.remove("title")
def isDisabled = attrs.remove("disabled")
if ("true".equals(isDisabled)) {
out << """<input title="${title}" disabled="${isDisabled}" """
attrs.each { k,v ->
out << k << "=\"" << v << "\" "
}
out << "/>"
} else {
out << """<input title="${title}" """
attrs.each { k,v ->
out << k << "=\"" << v << "\" "
}
out << "/>"
}
}
in your gsp, call your textfield tag like so
<g:myTextField title="${title}" disabled="${disabled}" />
adding extra attributes like so is also valid
<g:myTextField class="title" name="theName" value="theValue" title="${title}" disabled="${disabled}" />
make sure your ${disabled} variable returns "true" or "false" as strings this time.

Related

Simpler way to alternate upper and lower case words in a string

I recently solved this problem, but felt there is a simpler way to do it. I looked into inject, step, and map, but couldn't figure out how to implement them into this code. I want to use fewer lines of code than I am now. I'm new to ruby so if the answer is simple I'd love to add it to my toolbag. Thank you in advance.
goal: accept a sentence string as an arg, and return the sentence with words alternating between uppercase and lowercase
def alternating_case(str)
newstr = []
words = str.split
words.each.with_index do |word, i|
if i.even?
newstr << word.upcase
else
newstr << word.downcase
end
end
newstr.join(" ")
end
You could reduce the number of lines in the each_with_index block by using a ternary conditional (true/false ? value_if_true : value_if_false):
words.each.with_index do |word, i|
newstr << i.even? ? word.upcase : word.downcase
end
As for a different way altogether, you could iterate over the initial string, letter-by-letter, and then change the method when you hit a space:
def alternating_case(str)
#downcase = true
new_str = str.map { |letter| set_case(letter)}
end
def set_case(letter)
#downcase != #downcase if letter == ' '
return #downcase ? letter.downcase : letter.upcase
end
We can achieve this by using ruby's Array#cycle.
Array#cycle returns an Enumerator object which calls block for each element of enum repeatedly n times or forever if none or nil is given.
cycle_enum = [:upcase, :downcase].cycle
#=> #<Enumerator: [:upcase, :downcase]:cycle>
5.times.map { cycle_enum.next }
#=> [:upcase, :downcase, :upcase, :downcase, :upcase]
Now, using the above we can write it as following:
word = "dummyword"
cycle_enum = [:upcase, :downcase].cycle
word.chars.map { |c| c.public_send(cycle_enum.next) }.join("")
#=> "DuMmYwOrD"
Note: If you are new to ruby, you may not be familiar with public_send or Enumberable module. You can use the following references.
Enumberable#cycle
#send & #public_send

Pattern matching with tag in Lua

I'm trying to parse a text, and based on tags to do actions.
The text is:
<window>
<caption>My window
</window>
<panel>
<label>
<caption>
<position>50,50
<color>255,255,255
</label>
</panel>
Code:
function parse_tag(chunck)
for start_tag,tag_name in string.gfind(chunck,"(<(.-)>)") do
if (child_obj[tag_name]) then
print(start_tag)
for data,end_tag in string.gfind(chunck,"<" .. tag_name ..">(.-)(</" .. tag_name ..">)") do
for object_prop,value in string.gfind(data,"<(.-)>(.-)") do
print("setting property = \"" .. object_prop .. "\", value of" .. value);
end
end
print("</" .. tag_name ..">");
elseif(findInArray(main_obj,tag_name)) then
print("Invalid data");
stop();
end
end
end
for key,tag in ipairs(main_obj) do
for start_tag,tag_name,chunck,end_tag in string.gfind(data,"(<(" .. tag.name .. ")>)(.-)(</" .. tag.name .. ">)") do --> searching for window/panel start and end tags
if (findInArray(main_obj,tag_name)) then
print(start_tag)
parse_tag(chunck); --> parses the tag with child tag
print(end_tag)
end
end
end
It seems to fail getting the value, as I get the following output:
<window>
</window>
<panel>
<label>
setting property = "caption", value of
setting property = "position", value of
setting property = "color", value of
</label>
</panel>
How can I use match the string after the first <%tag%> until the next <%tag%> or end of the chunk.
string.gfind(data,"<(.-)>(.-)")
Here, you try to match the value with .-. However, - is lazy, i.e, .- will try to match as little as possible, in this case, an empty string.
Try telling it to match until the next <:
string.gfind(data,"<(.-)>(._)<")
Tried different type of captures.
This
string.gfind(data,"<(.-)>([^%<+.-%>+]+)")
Seems to work

Referencing <tmpl:myTemplate /> in grails taglib

I've created a tmpl gsp tag containing a bit of markup that's used throughout the forms in my webapp (/shared/formRow.gsp). I'd like to reference this tmpl gsp tag in a groovy taglib I've created. Is this possible?
Here's the def from my taglib...
def checkboxRow = { attrs ->
def name = attrs.name
def value = attrs.value
def label = attrs.label
def defaultLabel = attrs.defaultLabel
out << "<tmpl:/shared/formRow name='${name}' label='${label}' defaultLabel='${defaultLabel}'>"
out << " ${checkBox(id: name, name: name, value: value)}"
out << "</tmpl:/shared/formRow>"
}
I realise the syntax is a bit different in taglibs (e.g. you need to do ${checkBox(...)} rather than ), but is it possible to reference your own tmpl gsp tag in a similar way? If so, what syntax would I use?
Well, it turns out that it's in the Grails documentation, here.
You should just call the render template method like this:
def formatBook = { attrs, body ->
out << render(template: "bookTemplate", model: [book: attrs.book])
}
Simple really!

Ruby detecting if value is set in variable setting

I have a function generate_username that generates a username (obviously).
The values fname and lname are mandatory, so no issues there. However, mname is NOT a mandatory field so, it may be blank, which breaks this code.
Any suggestions on how to ask ruby to only print the mname value if it exists or is set and ignore it if the user left it blank?
def generate_username
self.username = fname.to_s.split("")[0] + mname.to_s.split("")[0] + lname.to_s
end
You could try this (parentheses are important):
def generate_username
self.username = fname.to_s.split("")[0] << (mname.to_s.split("")[0] || "") << lname.to_s
end
Throwing a simple ternary operator in to check if the value is blank? should do the trick.
def generate_username
self.username = fname.to_s.split("")[0] + (mname.blank? ? "" : mname.to_s.split("")[0]) + lname.to_s
end
In ruby 1.9
def generate_username
"#{fname[0]}#{mname.to_s[0]}#{lname}"
end
or
def generate_username
fname[0]+mname.to_s[0].to_s+lname
end
In ruby 1.8, replace all the [0] with [0, 1] (This point added after being pointed out by Peter).
mname.to_s ensures you get a string; when mname is nil it will be an empty string "".
String#[0] picks up the first character of that string; when the string is empty, it will return nil.
#{ } within " " expands the ruby code, and turns it into a string; particularly turns nil into an empty string "".

Removing a pattern from the beginning and end of a string in ruby

So I found myself needing to remove <br /> tags from the beginning and end of strings in a project I'm working on. I made a quick little method that does what I need it to do but I'm not convinced it's the best way to go about doing this sort of thing. I suspect there's probably a handy regular expression I can use to do it in only a couple of lines. Here's what I got:
def remove_breaks(text)
if text != nil and text != ""
text.strip!
index = text.rindex("<br />")
while index != nil and index == text.length - 6
text = text[0, text.length - 6]
text.strip!
index = text.rindex("<br />")
end
text.strip!
index = text.index("<br />")
while index != nil and index == 0
text = test[6, text.length]
text.strip!
index = text.index("<br />")
end
end
return text
end
Now the "<br />" could really be anything, and it'd probably be more useful to make a general use function that takes as an argument the string that needs to be stripped from the beginning and end.
I'm open to any suggestions on how to make this cleaner because this just seems like it can be improved.
gsub can take a regular expression:
text.gsub!(/(<br \/>\s*)*$/, '')
text.gsub!(/^(\s*<br \/>)*/, '')
text.strip!
class String
def strip_this!(t)
# Removes leading and trailing occurrences of t
# from the string, plus surrounding whitespace.
t = Regexp.escape(t)
sub!(/^(\s* #{t} \s*)+ /x, '')
sub!(/ (\s* #{t} \s*)+ $/x, '')
end
end
# For example.
str = ' <br /> <br /><br /> foo bar <br /> <br /> '
str.strip_this!('<br />')
p str # => 'foo bar'
You can use chomp! and slice! methods. See:
http://ruby-doc.org/core-1.8.7/String.html
def remove_breaks(text)
text.gsub((%r{^\s*<br />|<br />\s*$}, '')
end
%r{...} is another way to specify a regular expression. The advantage of %r is that you can pick your own delimeter. Using {} for the delimiters means not having to escape the /'s.
use replace method instead
str.replace("<br/>", "")

Resources