Proper method to access Play! cache in Scala templates? - session

I'm running a Play! app using Scala templates. However, I can't find an elegant method to access the Cache in an elegant (or valid) way inside of html templates.
I've tried everything like:
<some html>#play.cache.Cache.get(play.session.getId() + "-account")</some html>
But no luck. Thanks for the proper way to do this!

I found the methodology buried in the old 0.9 Scala documentation. For the time being it's not super-easy but it's 3min do-able. It requires adding a parameter to the controller and template like so:
In your controller, pass session as a parameter
object Application extends Controller {
import views.Application._
def index = {
html.index(session)
}
}
At the top of your template, define the implicit variable:
#(implicit session:play.mvc.Scope.Session)
Inside the template html, access it like so:
#(play.cache.Cache.get(session.getId() + "-account"))

Related

Is it possible to dynamically inject templates in Sinatra

I've got some (well, actually a whole lot) inline templates that all look alike that I'd rather not hard code. Is it possible to inject them dynamically somehow?
For example instead of:
__END__
##view1
==slim :defaultview
##view2
==slim :defaultview
...
I'd like to do something like...
%w[view1 view2].map{|v| templates[v] = "==slim :defaultview"} #templates would be Sinatra's internal template cache
Use named templates:
%w[view1 view2].map(&:to_sym)
.each do |v|
template v do
"==slim :defaultview"
end
end
If that's all each template does though, then I'm not sure why you'd create a template to wrap around the partial?

In a TextMate snippet, how can I pull in the current class and/or method name?

Just like I can pull in the currently selected text into a snippet using the $TM_SELECTED_TEXT, is there any way I can retrieve text from my code like the method name or class name containing the current caret position?
This'd be super useful for quickly creating useful log messages.
So, if I had some, say, JavaScript code (with | representing the cursor/caret location):
function doSomething() {
somethingElse();
|
}
I'd love to be able to spit out doSomething via a snippet.
Something like,
console.log($TM_CURRENT_METHOD_NAME + "() $1");
Is something like this possible?
In my fork of the Ember bundle, I put this script in Support/bin/camelize_filename:
#!/usr/bin/env ruby
c=%w{config helpers mixins controllers models routes templates views}.join('|')
r = %r{.*/(?:#{c})/(.*)\.js}
puts ENV['TM_FILEPATH'].sub(%r{.*/(?:#{c})/(.*)\.js},'\1').
gsub(/(?:_|(\/)|^)([a-z\d]*)/){|s| "#{$1}#{$2.capitalize}" }.gsub('/','')
Then I use it in snippets thusly:
console.groupCollapsed("`camelize_filename`#model");
You could adapt this for other frameworks by adapting the regex to match which directory segments belong in a class's namespace and which do not, and changing gsub('/','') if the language you are interested uses a namespace delimiter like '::'.

Spring MVC Portlets: external pagination with displaytag needs to go to the action phase

I'm using Spring MVC portlets I need to implement one display tag with external pagination. In order to do this, I've defined my table in the JSP like this:
<portlet:actionURL var="viewListURL">
<portlet:param name='action' value='${ServletContextKeys.MY_ACTION_METHOD}'/>
</portlet:actionURL>
<display:table name="${whateverList}"
requestURI="${viewListURL}"
class="displayTagTable"
export="true"
uid="item"
pagesize="10"
partialList="true"
sort="external"
defaultsort="1"
size="${ServletContextKeys.SC_LIST_SIZE}">
...
The problem is that, when I click any button to paginate, the displaytag redirects me to the render phase instead the action phase as I want to. What am I doing wrong? Any ideas..?
Thanks a lot
EDIT: I can see in the URL that the parameter p_p_url_type=0 (render phase). it makes no sense to me, as I'm calling an action url, but maybe would be enough just change this parameter to p_p_url_type=1. But, I'm just don't know how... Any ideas?
http://localhost:8080/wsdes/user/sifo3/home?p_p_id=SifoIIIweb_WAR_sifo3economicoweb_INSTANCE_s8jH&p_p_lifecycle=1&p_p_url_type=0&p_p_state=maximized&p_p_mode=view&_SifoIIIweb_WAR_sifo3economicoweb_INSTANCE_s8jH_action=consultaJustificantes&_SifoIIIweb_WAR_sifo3economicoweb_INSTANCE_s8jH_implicitModel=true&_SifoIIIweb_WAR_sifo3economicoweb_INSTANCE_s8jH_d-49489-p=2
Been there before. I solved the problem in a different way, but while looking in DisplayTag source code I found some interesting things. For example, in PortletHref you can find this in the addParameter method:
if (PARAM_TYPE.equals(name))
{
if (TYPE_RENDER.equals(value))
{
this.setAction(false);
}
else if (TYPE_ACTION.equals(value))
{
this.setAction(true);
}
And also:
private static final String PARAM_PREFIX = "portlet:";
public static final String PARAM_TYPE = PARAM_PREFIX + "type";
public static final String TYPE_ACTION = "action";
Apparently, if you need a parameter named portlet:type with value action to make DisplayTag generate an Action URL. I haven't tested myself, so let me know if it works.
I still don't know the reason, but I fixed this issue changing the display tag for Portlets (displaytag-portlet.jar), to the standard displaytag, and deleting from the displaytag.properties file the factory.requestHelper property:
factory.requestHelper=org.displaytag.portlet.PortletRequestHelperFactory
Using the normal displaytag library, instead of the portlet one, fixed my problems.

render individual file in middleman

I am writing a helper and I need to get a rendered file as String.
I see that the method that I need exists in the middleman's library: http://rubydoc.info/github/middleman/middleman/Middleman/CoreExtensions/Rendering/InstanceMethods#render_individual_file-instance_method
How do I call this function from my helper class?
I tried:
require "middleman-core/lib/middleman-core/core_extensions/rendering.rb"
...
puts Middleman::CoreExtensions::Rendering::InstanceMethods.render_individual_file(filepath)
But it does not seem to find the file, any idea?
I'm not sure 3.0 beta is quite ready for primetime.
That said, it does sound like the partial method is what you're looking for.
Unless I'm missing something, the Middleman method seems like an overly-complex solution. For one of my sites I wanted to load entire text files into my templates, so I wrote this helper:
# Shortcut for loading raw text files. Obviously assumes that given file is in a valid format.
# #return [String] File contents
def load_textfile(filename)
File.read filename.to_s
end
Also, you should clarify if you are intending to use this within a template, or within Ruby code. It's not clear to me based on your question.
Here is an example of how one would use above helper:
Currently of note, Middleman is in the process of transitioning to version 4, and the conventions for loading helpers will change. The most straightforward way to define a helper is within a helper block in your config.rb file, as follows:
helpers do
# Define helper functions here to make them available in templates
end
I use Slim for templating. It really is the best. In slim you would appply helper as thus:
= load_textfile 'path'
p You can embed helper output in your page with interpolation, too: #{load_textfile 'path'}

Trouble creating custom routes in Ruby on Rails 3.1

I can't seem to set up a custom URL. All the RESTful routes work fine, but I can't figure out how to simply add /:unique_url to the existing routes, which I create in the model (a simple 4 character random string) and will serve as the "permalink" of sorts.
Routes.rb
resources :treks
match ':unique_url' => 'treks#mobile'
Controller
.
.
def mobile
#trek = trek.find(params[:id])
end
Is this because I'm trying to define a custom action on an existing resource? Can I not create custom methods on the same controller as one with a resource?
By the way, when I change routes.rb to match 'treks/:id/:unique_url' => treks#mobile it works fine, but I just want the url to simply be /:unique_url
Update It seems like find_by_[parameter] is the way to go...
I've been playing in console and I can't seem to get any methods to come forward...I can run Trek.last.fullname for example, but cannot run #trek = Trek.last...and then call...#trek.lastname for example. Any clues why? I think this is my issue.
So is there a field on Trek which stores its unique url? If so you should be doing something like this:
#trek = Trek.find_by_url(params[:unique_url])
trek.find_by_unique_url( params[:unique_url] ) # should do the trick
#pruett no, the find_by_XXX methods are generated on-the-fly via Ruby's method_missing call! So instead of XXX you can use any of the attributes which you defined in a model.
You can even go as far as listing multiple attributes, such as:
find_by_name_and_unique_url( the_name, the_unigue_url)
Check these pages:
http://guides.rubyonrails.org/active_record_querying.html
http://m.onkey.org/active-record-query-interface
if you get a undefined method ... for nil:NilClass , it means that the object you are trying to call that method on does not exist, e.g. is nil.
You probably just missed to put an if-statement before that line to make sure the object is non-nil
Hmm. I usually would do something like this:
map.connect "/:unique_url", :controller => "treks", :action => "mobile"
Then in that controller the ID isn't going to be applicable.. you'd need to change it to something like this:
def mobile
#trek = trek.find_by_unique_url(params[:unique_url])
end
(that's if unique_url is the column to search under)

Resources