MVC (spark view engine) Whats the difference between x and m? - asp.net-mvc

I came across something strange/weird when coding a spark file. I knew about Html.TextBoxFor, but i noticed my view was rendering it as pure text when i used this:
${Html.TextBoxFor(x => x.Name}}
But when i changed it to this it worked:
${Html.TextBoxFor(m => m.Name)}
the m here probably stands for Model as i've declared the mode like so at the top of the .spark file:
<viewdata model="Test.Models.RegisterViewModel" />
But x or m should be a delegate declaration or something. Could anyone tell me why x wont work in this case? Shouldnt it assume that everything i put in as x or m would be the model I've declared at the top of the page?

Copied from your question:
${Html.TextBoxFor(x => x.Name}}
${Html.TextBoxFor(m => m.Name)}
In the top one (using x) you have two closing curly braces instead of a parentheses and a brace.
In the second one (using m), you have the correct closing parentheses and brace. I can imagine that's why Spark rendered it as pure text in the top instance because it didn't recognise a code block there since you were missing a close paren.

There is no difference between the two . The variable is like a counter used in for ( a local variable that defines the common action taken upon all objects within the lambda expression.
The reason why that worked is probably the fact that you had an error in your previous code syntax, or you forgot to build
my 2 cents
Disclaimer:
I didn;t see the spark tag ... This answer is totally dedicated to the MVC aspect of the issue

Related

How do directives work in Spray?

I'd like to understand how directives in Spray work. As per the documentation:
The general anatomy of a directive is as follows:
name(arguments) { extractions =>
... // inner Route
}
My basic understanding is that in the below snippet, 32 is passed as a parameter to method test.
test {
32
}
However, in the above directive name example, it is said arguments are passed into inner route, which is an anonymous function.
Could someone please help me understand the syntax and the flow starting from how the arguments are extracted and passed into an inner route?
You're right that that syntax passes 32 to the function test. What you're missing is that a Directive accepts a function as an argument (remember, we're doing functional programming now so functions are values). If you wanted to write this:
path(IntNumber) {
userId =>
complete(s"Hello user $userId")
}
in a less DSL-ey fashion, you could do this:
val innerFunction: Int => Route = {userId => complete(s"Hello user $userId")}
(path(IntNumber))(innerFunction)
or even this:
def innerMethod(userId: Int): Route = complete(s"Hello user $userId")
(path(IntNumber))(innerMethod)
The mechanics of how this is actually accomplished are... complex; this method makes a Directive implicitly convertible to a function:
implicit def pimpApply[L <: HList](directive: Directive[L])(implicit hac: ApplyConverter[L]): hac.In ⇒ Route = f ⇒ directive.happly(hac(f))
This is using the "magnet pattern" to select an appropriate hac, so that it can take a function in the inner path (with an appropriate number of arguments) if the directive extracts parameters, or a value in the inner path (a plain route) if the directive doesn't extract parameters. The code looks more complicated than it is because scala doesn't have direct support for full dependent typing, so we have to emulate it via implicits. See ApplyConverterInstances for the horrible code this necessitates :/.
The actual extracting all happens when we get an actual route, in the happly method of the specific directive. (If everything used HList everywhere, we could mostly avoid/ignore the preceding horrors). Most extract-ey directives (e.g. path) eventually call hextract:
def hextract[L <: HList](f: RequestContext ⇒ L): Directive[L] = new Directive[L] {
def happly(inner: L ⇒ Route) = ctx ⇒ inner(f(ctx))(ctx)
}
Remember a Route is really just a RequestContext => Unit, so this returns a Route that, when passed a RequestContext:
Runs f on it, to extract the things that need extracting (e.g. URL path components)
Runs inner on that; inner is a function from e.g. path components to the inner route.
Runs that inner route, on the context.
(The following was edited in by a mod from a comment conversation):
Fundamentally it's pretty elegant, and it's great that you can see all the spray code and it's ordinary scala code (I really recommend reading the source when you're confused). But the "bridging" part with the ApplyConverter is complex, and there's really no way around that; it comes of trying to do full dependent types in a language that wasn't really designed for them.
You've got to remember that the spray routing DSL is a DSL; it's the kind of thing that you'd have to have as an external config file in almost any other language. I can't think of a single web framework that offers the same flexibility in routing definitions that spray does with complete compile-time type safety. So yes, some of the things spray does are complex - but as the quote goes, easy things should be easy and hard things should be possible. All the scala-level things are simple; spray is complex, but it would be even more complex (unusably so) in another language.

ist there something like __FILE__ in coffeescript at 'compiletime'?

The question:
How do I get somthing like that in coffeescript
modules_list[some_calculation(__FILE__)]=a_local_class.new
I have a module manager, that handles all my coffeescripts (js) at runtime - i.e. while in browser, that means:
I have
many modules, not all are in all situations loaded 'statically'
only some have dependencies
module manager resolves things like init and dynamic reload (ajax)
and dynamic init
A module looks like this in prinzip:
class Book
constructor: ->
...
init: =>
$$$.get_module('BookReader') #<- ajax loaded if not already
later_on: =>
$$$.get_module('LetterCounter').count_letters(#) #<- ajax loaded if not already
...
#$$$.modules_list['Book'] = ->
new Book
this all works (very) satisfying.
But I have a rendunancy in my Logic, because a 'module', has a module name, a class name and - thats the point - a file name
the class name is - thats clear - not a problem, I could name all 'Foo'. Its only not nice to do that.
But modulename ( modules_list['Book'] ) and the coffee- (js-) file name are redundant in sence of Rails CoC.
Any ideas how to get
#$$$.modules_list[some_calc(__FILE__)] = -> new Book
i was there, and there may be a solution for me, but if, I dont understand it.
thanks in advance
ps.: for those who want to know "why I do this":
I have 3 completely different apps for 3 different customers, I am far away to say what is the base for all, 2 apps a realy big with a huge amount of js, that is not always needed so I want to reload it dynamicaly. I "help" asset pipeline a bit with putting all files (staticaly) used in a single one without the ones I was working on the last 20 mins (dynamicaly) for better debugging, and I get rid of all (down-)load ordering problems
There is no need for __FILE__or something like that, in that case. I see that now. It would be the wrong direction of naming.
Its the same 'problem' that you have with Rails it self. If you have
module Base
class Fun
your filename should be base/fun.rb not vice versa!
The Filename resolves out of "its content" not the other direction.

Change format of inline code evaluation in org-mode's LaTeX-export

I have a code block in an org document
#+NAME: result_whatever
#+BEGIN_SRC python :session data :results value :exports none
return(8.1 - 5)
#+END_SRC
which I evaluate inline:
Now, does this work? Let's see: call_result_whatever(). I'd be surprised ...
When exporting to LaTeX, this generates the following:
Now, does this work? Let's see: \texttt{3.1}. I'd be surprised \ldots{}
However, I don't want the results to be displayed in monospace. I want it to be formatted in "normal" upright font, without any special markup.
How can I achieve this?
You should be able to get it work using the optional header arguments which can be added to call_function().
I don't have LaTeX installed on this system so can't fully test the outputs to ensure they come out exactly as desired, I'm using the plain text output to compare instead. However you can use the following syntax as part of your call to modify the results.
Now, does this work? Let's see call_results_whatever()[:results raw].
I'd be surprised ...
Without the [:results raw] the output to Plain Text (Ascii buffer) is Let's see `3.0999999999999996'.. With the added results it becomes Let's see 3.0999999999999996.
For full details of the available results keywords as well as other optional header arguments for the inline blocks please see Evaluation Code Blocks and Results arguments.
this is 5 years later. apparently in org-mode 8.2 or so, a new variable was introduced (documenting in "Evaluating Code Blocks" in the org-mode manual, but this from etc/ORG-NEWS in the source tree):
*** New option: org-babel-inline-result-wrap
If you set this to the following
: (setq org-babel-inline-result-wrap "$%s$")
then inline code snippets will be wrapped into the formatting string.
so, to eliminate \texttt{}
(setq org-babel-inline-result-wrap "%s")
The problem of this type can be solved in two ways:
1: Easy does it:
A plain query-replace on the exported buffer.
Once you're in the LaTeX buffer,
beginning-of-buffer or M-<
query-replace or M-%
enter \texttt as the string that you want to replace
enter nothing as the replacement
continue to replace each match interactively
with y/n or just replace everything with !
2: But I wanna!
The second way is to nag the org-mode mailing list into
implementing a switch or an option for your specific case.
While it's necessary sometimes, it also produces a system
with thousands of switches, which can become unwieldy.
You can try, but I don't recommend.

Would you like ASP.NET MVC view engine in which a view is created entirely in Code?

Recently I created a spike of a view engine, in which views are plain classes, and the content is created by using funny using-scope blocks.
The code together with a simple sample site is available at http://code.google.com/p/sharp-view-engine/
Here I'd like to hear your opinions regarding such an idea. Is it completely weird or maybe someone likes it?
I would actually not like that.
I can agree with DSLs (such as a Parser-Combinator or for generating XML Nodes in a data-context), but in this case I think that too much is being put in code that. And, in the end, this just complicates boundaries and leads to hard-to-maintain code. (You can already do the same, but with more verbosity just using the "standard" Web Controls. You can always use {subblock} in C# to limit a variables scope.)
The approach I prefer to use is templates with bindings (but no "code in templates"). That makes it easy for the "designer" (hopefully not me, or the next person to come along and) edit the layout of the view how they see fit. However, the core logic (the available controls and bindings) are kept in the code -- uncluttered. (Another advantage with the templates is that if they externally housed they do not require a recompile for every little change.)
Simplicity and maintainability are like ... zen.
This is an interesting idea taken to the extreme I'd say. At my shop we're using html conventions for pretty much everything except our layout. The only real html we have in the project is our Spark master page. For generating the content itself we use a convention engine that that spits out a semantic html model. (We're using the HtmlTags library from FubuMVC to build the semantic model.)
An example convention for rendering a multiline text box looks like:
public static HtmlTag Build(ElementRequest req)
{
return Tags.TextArea
.Rows(6)
.Id(req.ElementId)
.Attr("name", req.ElementId)
.Text(req.StringValue());
}
These conventions get triggered from reflecting on the view model (or we can manually call them from a helper method). The output is rendered (via ToString()) into the content section of our master page. We're joking that pretty soon we won't even need a view engine.
ps here's how we handle nesting. (Your using blocks look cluttered!)
return Tags.Div.Nest(
Tags.Button("save").AddClass("positive"),
Tags.Span.Text(" or "),
Tags.Anchor.Text("cancel").AddClass("negative")
);
Nest() is an extension method that simply takes a params array of HtmlTag and appends them to the parent's children collection.

Problems with Netbeans re: Rails erb/rhtml intellisense?

I've been using Netbeans for Rails and like it a lot, considering how little I paid for it. But something that bothers me is that when I'm editing an RHTML or ERB file, it doesn't do the code autocomplete - or at least not reliably. Sometimes it shows the appropriate variables and methods that are available on an object after you type the dot operator. Sometimes it ignores the instance variables. Is there a solution for this? (Please don't say RadRails).
Oh and one more thing in case anyone has solved this: considering how often I have to type <% when I'm in a Rails template, I wish there was some hotkey for autotyping the tag . . . ? I always have to stop and look down at my keyboard to find the < and % keys before I can type the tag so it's not as trivial as it might sound.
I believe you're looking for something like this:
http://ruby.netbeans.org/codetemplates-rhtml.html
Type in one of the triggers, then hit the tab key to expand it to the code as given.
Also, you might want to explore using HAML. It's much easier on the hands.

Resources