How to check for resource file existence at run-time [grails]? - spring

I need to test whether a resource file (an image, for instance) exists and if not, I will display another image.
My GSP view code looks like:
<% if (resExists(dir: "images", file:"img.jpg")) {%>
<img src="${g.resource(dir:'images',file: 'img.jpg')}">
<% else { %>
<img src="${g.resource(dir:'images',file: 'noimg.jpg')}">
<%}%>
How can I test for a file existence in Grails? What is the code of the method boolean resExists()

I found out the answer:
def resExists(resPath) {
def resFile = grailsApplication.parentContext.getResource(resPath)
resFile?.exists()
}
or
def resExists(resPath) {
def resFile = request.servletContext.getResource(resPath)
resPath
}
And you call it with resExists('images/img.jpg')

I've done the following in GSP:
<g:set var="flag" value="${new File(grailsApplication.mainContext.servletContext.getRealPath("images/sgs-geosol/sign/${sec.username()}.gif")).exists()}"></g:set>
<g:if test="${flag}">
</g:if>
The code below returns the real path of the Grails app:
grailsApplication.mainContext.servletContext.getRealPath("")

The above answer did not work for me when used from within a plugin, packaged as a production war. I now use the following:
GrailsConventionGroovyPageLocator groovyPageLocator
def resExists(resPath) {
def resource = groovyPageLocator.findTemplateByPath(resPath)
resource
}

Related

How to handle dependencies in puppet from parent class

Main problem: I have some dynamic code in parent class, in subclass I am including additional resource. I want to add the resource to catalog from child before executing parent level.
Could you propose me good dependency command or a tip how to write it another way.
Sample code may be helpful here.
Manifest file
class class1 {
file {'C:/Temp/test1':
content => 'test1',
}
}
class parent {
file {'C:/Temp/test2':
content => template('parent/test2.erb')
}
}
class parent::child {
file {'C:/Temp/test3':
content => 'test3'
}
}
Class['class1']->Class['parent::child']
include class1
include parent::child
test2.erb
<% scope.catalog.vertices.each do |resource| -%>
<%= resource -%>
<% end -%>
Result: test2
Stage[main] Class[Settings] Class[main] Class[Class1] File[C:/Temp/test1] Class[Parent]
I want it also to include
File[C:/Temp/test3]
It is not answer, since I didn't get all information for your question.
First I simplify your code, if you think that makes sense, we can start the discussion from it.
Manifest file:
class class1 {
file {'C:/Temp/test1':
content => 'test1',
}
}
->
class parent {
file {'C:/Temp/test2':
content => template('parent/test2.erb')
}
}
include class1
include parent
test2.erb
<% scope.catalog.vertices.each do |resource| -%>
<%= resource -%>
<% end -%>

error undefined method in method call by pressing bootstrap button on index page Rails 4

I need to call method download_images("\folder","http:\url") which save pictures from url in choosen directory.This method should be called in index.html.erb and grab folder address from textbox1 and url from textbox2 after pressing the button1.
Right now I don't know how to grab strings from textboxes, I am trying to call method correctlyThe index.html.erb code:
<h1>Welcome#index</h1>
<p><%= "Download pictures from url!" %></p>
<div class="form-horizontal">
<p> Input url: </p>
<p> <input type="text"/> </p>
<p> Input destination folder: </p>
<p> <input type="text"/> </p>
<button class="btn">Go!</button>
<% button_to "btn", :method=> download_images("`/tutorial1/downloadedpics","http://www.yandex.ru/") %>
</div>
I defined method download_images in welcome_controller.rb:
class WelcomeController < ApplicationController
def index
end
def download_images(url, destination_path, options = {})
base_url = URI.join(url, "/").to_s
body = Typhoeus::Request.get(url).body
imgs = Nokogiri::HTML(body).css("img")
image_srcs = imgs.map { |img| img["src"] }.compact.uniq
hydra = Typhoeus::Hydra.new(:max_concurrency => options[:max_concurrency] || 50)
image_paths = image_srcs.map do |image_src|
image_url = URI.join(base_url, image_src).to_s
path = File.join(destination_path, File.basename(image_url))
request = Typhoeus::Request.new(image_url)
request.on_complete { |response| File.write(path, response.body) }
hydra.queue(request)
path
end
hydra.run
image_paths
end
end
After I switch server and go to localhost, I receive an exception:
NoMethodError in Welcome#index, undefined method download_images' for #<#<Class:0x007f202fc3ae50>:0x007f202f9ab518>, in line <% button_to "btn", :method=> download_images("/tutorial1/downloadedpics","http://www.yandex.ru/") %>
I am a noob programmer, so I can do rather dumb mistakes...
And it is important to mention: I work in Nitrous web box, and don't really know is it possible to download images in box folder:
~/tutorial1/downloadedpics
Also I use Bootstrap controllers,Nokogiri gem and Typhoeus gem.
Ruby version:ruby 2.1.1p76
Rails version:Rails 4.1.0
Thank you for your attention.
As a FYI, doing:
imgs = Nokogiri::HTML(body).css("img")
image_srcs = imgs.map { |img| img["src"] }.compact.uniq
is not the right way to find images with "src" parameters. Because you're not searching correctly, you get nils in your resulting array, forcing you to use compact. Instead, don't rely on cleaning up after making a mess, just avoid making the mess in the first place:
require 'nokogiri'
body = <<EOT
<html>
<body>
<img>
<img src="foo">
</body>
</html>
EOT
imgs = Nokogiri::HTML(body).css("img[#src]")
image_srcs = imgs.map { |img| img["src"] }
image_srcs # => ["foo"]

Referencing controller variables in bootstrap tooltip

If a tweet contains any phrase that belongs to the current user's blockedshow, it receives the redacted div. I want the tooltip to tell the user which specific phrase the tweet contains, when it hovers over the tweet. Right now Im using #phrases and it's not working. Any ideas?
View
<% if is_redacted? tweet %>
<!-- Tweet contains at least one blocked phrase. -->
<a href="https://www.twitter.com/#{tweet.user.screen_name}"
data-toggle="tooltip" title="This tweet contains the phrase:<%=#phrases%> ">
<%= check_if_redacted(tweet.text)%>
</a>
<% end %>
Controller
class TwitterController < ApplicationController
def index
end
def login
end
def tweet
text = params[:my_tweet]
Client.update(text) unless text==nil
end
private
def is_redacted? tweet
#phrases ||= current_user.blockedshows.map(&:phrases).flatten.map(&:text)
#phrases.any? { |phrase| tweet.text.include? phrase }
end
helper_method :is_redacted?
end
The instance variable #phrases is defined in a helper method. I don't think it is visible in the view scope. You need to initate in the controller action instead. If this is in the index:
def index
#phrases = current_user.blockedshows.map(&:phrases).flatten.map(&:text)
end
I am a bit confused by your tweet method. Is this a controller action or just a helper method. I looks like a helper method since you are referring to it in the view (unless there is more code not seen here). I would put tweet in an instance variable also and maybe even is_redacted. Seomthing like:
def index
#phrases = current_user.blockedshows.map(&:phrases).flatten.map(&:text)
#tweet = Client.update(params[:my_tweet]) unless text==nil
#isredacted = #phrases.any? { |phrase| tweet.text.include? phrase }
end
and then use it in the view:
<% if #isredacted %>
<!-- Tweet contains at least one blocked phrase. -->
<a href="https://www.twitter.com/#{#tweet.user.screen_name}"
data-toggle="tooltip" title="This tweet contains the phrase:<%=#phrases%> ">
<%= check_if_redacted(#tweet.text)%>
</a>
<% end %>

Rendering a partial with different content blocks on the same page: i need a partial helper that accepts a content block

I really like how Sass mixins let you wrap a block of code with a customizable wrapper:
=container($class)
.#{$class}.container
.container-inner
#content
+container(header)
foo: bar
+container(main)
baz: quux
Resulting CSS:
.header.container .container-inner {
foo: bar;
}
.main.container .container-inner {
baz: quux;
}
I'm trying to do the same with Padrino/Middleman partials. The problem is that partials not accept content blocks (whyyy?). :(
I tried to work it around by passing content blocks into content_for, but subsequent uses of content_for would append to content rather than replace it:
Partial partials/container.haml:
.container
= yield_content :container
Page index.html.haml:
- content_for :container do
Foo
= partial('partials/container')
- content_for :container do
Bar
= partial('partials/container')
Resulting HTML:
<div class="container">
Foo
</div>
<div class="container">
Foo
Bar
</div>
As you can see, it duplicates my content which is absolutely unacceptable. Also, this way does not allow to provide arguments that would be used to customize wrapper HTML.
So i thought of creating a helper. It would enable the following usage style which is way more elegant than content_for and also supports passing variables into content block:
= partial_with_content_block('partials/container', class: 'header') do
Foo
= partial_with_content_block('partials/container', class: 'main') do
Bar
How do i implement such a helper?
Something like this should work, but I left the partial out:
def container(options={}, &block)
raise ArgumentError, "Missing block" unless block_given?
content = capture_html(&block)
content_tag(:div, content, options)
end
Call as:
= container(class: 'main') do
p More content here
But now that I think if it, this could be all handled with default Padrino methods:
= content_tag :div, class: 'main' do
p More content
Middleman partials do accept content blocks, but the syntax is slightly different. ERB is given below, but you should be able to do this in HAML, as well.
<% partial 'my_partial' do %>
My Content
<% end %>
my_partial.html.erb
<p>
<%= yield %>
</p>
Result
<p>
My Content
</p>

How to replace a node by a ruby string?

I'm trying to replace all my <img> tags in an HTML file by <%= image_tag() %> rails tag.
What I want to do is something like:
doc = open("myfile.html") { |f| Hpricot(f) }
imgs = doc.search("//img") # here i got all Hpricot::Elements
imgs.each { |i|
# fake function name !
i.replace_by_HTML('<%= image_tag("/images/blabla.jpg") %>')
}
What I need it a function that will replace the node in the file by a string I would pass.
< img src="/images/blalba.jpg" /> would give => <%= image_tag("/images/blabla.jpg") %>
Update:
I don't really want to use regular expressions, thats why I choosed Hpricot, because it will parse the HTML for me and then I can do Element.attributes and generate my image_tag with all the attributes included.
What if my img tags are like:
< img style="float:left;" src="images/blabla.jpg" width="30" height="30" ... />
or
< img src=\"images/blabla.jpg\" style=\"float:left;\" width=\"30\" height=\"30\" ... />
See what I mean? I may parse a .SQL file containing escaping slashes, the src attribute could be after another attribute, etc ...
The thing is I already did the function that will return my an image_tag if i give an Hpricot::Element, but I don't know how to replace the original node by my string in the Hpricot doc.
You can do this with gsub string method and regular expresions
doc = open("myfile.html") { |f|
f.read().gsub(/<img src="([^"]*)".*\/>/, '<%= image_tag("\1") %>')
}
I don't have hpricot installed but it seems (check this hpricot-altering) that you coud use swap method on searched elements
imgs.each { |i|
i.swap('<%= image_tag(' + i.src + ') %>')
}

Resources