Module: Innate::Node
- Includes:
- Traited
- Defined in:
- lib/innate/node.rb
Overview
The nervous system of Innate, so you can relax.
Node may be included into any class to make it a valid responder to requests.
The major difference between this and the old Ramaze controller is that every Node acts as a standalone application with its own dispatcher.
What’s also an important difference is the fact that Node is a module, so we don’t have to spend a lot of time designing the perfect subclassing scheme.
This makes dispatching more fun, avoids a lot of processing that is done by Rack anyway and lets you tailor your application down to the last action exactly the way you want without worrying about side-effects to other Nodes.
Upon inclusion, it will also include Trinity and Helper to provide you with Request, Response, Session instances, and all the standard helper methods as well as the ability to simply add other helpers.
Please note that method_missing will not be considered when building an Action. There might be future demand for this, but for now you can simply use ‘def index(*args); end` to make a catch-all action.
Constant Summary collapse
- NODE_LIST =
Set.new
Instance Attribute Summary collapse
-
#layout_templates ⇒ Object
readonly
Returns the value of attribute layout_templates.
-
#method_arities ⇒ Object
readonly
Returns the value of attribute method_arities.
-
#view_templates ⇒ Object
readonly
Returns the value of attribute view_templates.
Class Method Summary collapse
- .generate_mapping(object_name = self.name) ⇒ Object
-
.included(into) ⇒ Object
Upon inclusion we make ourselves comfortable.
-
.setup ⇒ Object
node mapping procedure.
Instance Method Summary collapse
-
#action_found(action) ⇒ Innate::Response
Executed once an Action has been found.
-
#action_missing(path) ⇒ Object
The default handler in case no action was found, kind of method_missing.
-
#alias_view(to, from, node = nil) ⇒ Object
Aliasing one view from another.
-
#binding ⇒ Binding
For compatibility with new Kernel#binding behaviour in 1.9.
-
#call(env) ⇒ Array
This makes the Node a valid application for Rack.
- #fill_action(action, given_name) ⇒ Action?
-
#find_aliased_view(action_name, wish) ⇒ nil, String
Resolve one level of aliasing for the given
action_name
andwish
. -
#find_layout(name, wish) ⇒ Array?
Try to find a suitable value for the layout.
-
#find_method(name, params) ⇒ String, Symbol
We check arity if possible, but will happily dispatch to any method that has default parameters.
-
#find_provide(path) ⇒ Array
Resolve possible provides for the given
path
from #provides. -
#find_view(action_name, wish) ⇒ String?
Try to find the best template for the given basename and wish and respect aliased views.
-
#layout(layout_name = nil, &block) ⇒ Proc, String
Define a layout to use on this Node.
-
#layout_mappings ⇒ Array<String>+
Combine Innate.options.layouts with either the ‘ancestral_trait` or the #mapping if the trait yields an empty Array.
-
#map(location) ⇒ Object
Shortcut to map or remap this Node.
-
#map_layouts(*locations) ⇒ Node
Set the paths for lookup below the Innate.options.layouts paths.
-
#map_views(*locations) ⇒ Node
Set the paths for lookup below the Innate.options.views paths.
-
#mapping ⇒ String
Tries to find the relative url that this Node is mapped to.
-
#needs_method? ⇒ true, false
Whether an Action can be built without a method.
- #options ⇒ Object
-
#patterns_for(path) ⇒ Action
The innate beauty in Nitro, Ramaze, and Innate.
-
#possible_exts_for(wish) ⇒ Array
Answer with an array of possible extensions in order of significance for the given
wish
. -
#possible_paths_for(mappings) ⇒ Array
Answer with an array of possible paths in order of significance for template lookup of the given
mappings
. -
#provide(format, param = {}, &block) ⇒ Object
Specify which way contents are provided and processed.
-
#provide_set? ⇒ true, false
This will return true if the only provides set are by Node::included.
- #provides ⇒ Object
-
#resolve(path) ⇒ nil, Action
Let’s get down to business, first check if we got any wishes regarding the representation from the client, otherwise we will assume he wants html.
-
#root_mappings ⇒ Array
make sure this is an Array and a new instance so modification on the wrapping array doesn’t affect the original option.
-
#to_layout(action_name, wish) ⇒ nil, String
Find the best matching action_name for the layout, if any.
-
#to_template(path, wish) ⇒ nil, String
Try to find a template at the given
path
forwish
. -
#to_view(action_name, wish) ⇒ String?
Try to find the best template for the given basename and wish.
-
#try_resolve(path) ⇒ Response
Let’s try to find some valid action for given
path
. - #update_layout_mappings ⇒ Object
- #update_mapping_shared(paths) ⇒ Object
-
#update_method_arities ⇒ Hash
Answer with a hash, keys are method names, values are method arities.
- #update_template_mappings ⇒ Object
- #update_view_mappings ⇒ Object
-
#view_mappings ⇒ Array<String>+
Combine Innate.options.views with either the ‘ancestral_trait` or the #mapping if the trait yields an empty Array.
Methods included from Traited
#ancestral_trait, #ancestral_trait_values, #class_trait, #each_ancestral_trait, #trait
Instance Attribute Details
#layout_templates ⇒ Object (readonly)
Returns the value of attribute layout_templates.
31 32 33 |
# File 'lib/innate/node.rb', line 31 def layout_templates @layout_templates end |
#method_arities ⇒ Object (readonly)
Returns the value of attribute method_arities.
31 32 33 |
# File 'lib/innate/node.rb', line 31 def method_arities @method_arities end |
#view_templates ⇒ Object (readonly)
Returns the value of attribute view_templates.
31 32 33 |
# File 'lib/innate/node.rb', line 31 def view_templates @view_templates end |
Class Method Details
.generate_mapping(object_name = self.name) ⇒ Object
86 87 88 89 90 91 92 |
# File 'lib/innate/node.rb', line 86 def self.generate_mapping(object_name = self.name) return '/' if NODE_LIST.size == 1 parts = object_name.split('::').map{|part| part.gsub(/^[A-Z]+/){|sub| sub.downcase }.gsub(/[A-Z]+[^A-Z]/, '_\&') } '/' << parts.join('/').downcase end |
.included(into) ⇒ Object
Upon inclusion we make ourselves comfortable.
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/innate/node.rb', line 58 def self.included(into) into.__send__(:include, Helper) into.extend(Trinity, self) NODE_LIST << into return if into.provide_set? into.provide(:html, :engine => :Etanni) into.trait(:provide_set => false) end |
.setup ⇒ Object
node mapping procedure
when Node is included into an object, it’s added to NODE_LIST when object::map(location) is sent, it maps the object into DynaMap when Innate.start is issued, it calls Node::setup Node::setup iterates NODE_LIST and maps all objects not in DynaMap by using Node::generate_mapping(object.name) as location
when object::map(nil) is sent, the object will be skipped in Node::setup
79 80 81 82 83 84 |
# File 'lib/innate/node.rb', line 79 def self.setup NODE_LIST.each{|node| node.map(generate_mapping(node.name)) unless node.trait[:skip_node_map] } # Log.debug("Mapped Nodes: %p" % DynaMap.to_hash) unless NODE_LIST.empty? end |
Instance Method Details
#action_found(action) ⇒ Innate::Response
Executed once an Action has been found.
Reset the Response instance, catch :respond and :redirect. Action#call has to return a String.
294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/innate/node.rb', line 294 def action_found(action) response = catch(:respond){ catch(:redirect){ action.call }} unless response.respond_to?(:finish) self.response.write(response) response = self.response end response['Content-Type'] ||= action.[:content_type] response end |
#action_missing(path) ⇒ Object
The default handler in case no action was found, kind of method_missing. Must modify the response in order to have any lasting effect.
Reasoning:
-
We are doing this is in order to avoid tons of special error handling code that would impact runtime and make the overall API more complicated.
-
This cannot be a normal action is that methods defined in Innate::Node will never be considered for actions.
To use a normal action with template do following:
341 342 343 344 345 346 347 348 |
# File 'lib/innate/node.rb', line 341 def action_missing(path) response = Current.response response.status = 404 response['Content-Type'] = 'text/plain' response.write("No action found at: %p" % path) response end |
#alias_view(to, from, node = nil) ⇒ Object
Aliasing one view from another. The aliases are inherited, and the optional third node
parameter indicates the Node to take the view from.
The argument order is identical with ‘alias` and `alias_method`, which quite honestly confuses me, but at least we stay consistent.
Note that the parameters have been simplified in comparision with Ramaze::Controller::template where the second parameter may be a Controller or the name of the template. We take that now as an optional third parameter.
604 605 606 607 |
# File 'lib/innate/node.rb', line 604 def alias_view(to, from, node = nil) trait[:alias_view] || trait(:alias_view => {}) trait[:alias_view][to.to_s] = node ? [from.to_s, node] : from.to_s end |
#binding ⇒ Binding
For compatibility with new Kernel#binding behaviour in 1.9
865 |
# File 'lib/innate/node.rb', line 865 def binding; super end |
#call(env) ⇒ Array
This makes the Node a valid application for Rack. env
is the environment hash passed from the Rack::Handler
We rely on correct PATH_INFO.
As defined by the Rack spec, PATH_INFO may be empty if it wants the root of the application, so we insert ‘/’ to make our dispatcher simple.
Innate will not rescue any errors for you or do any error handling, this should be done by an underlying middleware.
We do however log errors at some vital points in order to provide you with feedback in your logs.
A lot of functionality in here relies on the fact that call is executed within Current#call which populates the variables used by Trinity. So if you use the Node directly as a middleware make sure that you #use Innate::Current as a middleware before it.
259 260 261 262 263 264 265 |
# File 'lib/innate/node.rb', line 259 def call(env) path = env['PATH_INFO'] path << '/' if path.empty? response.reset try_resolve(path).finish end |
#fill_action(action, given_name) ⇒ Action?
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 |
# File 'lib/innate/node.rb', line 412 def fill_action(action, given_name) needs_method = self.needs_method? wish = action.wish patterns_for(given_name) do |name, params| method = find_method(name, params) next unless method if needs_method next unless method if params.any? next unless (view = find_view(name, wish)) or method params.map!{|param| Rack::Utils.unescape(param) } action.merge!(:method => method, :view => view, :params => params, :layout => find_layout(name, wish)) end end |
#find_aliased_view(action_name, wish) ⇒ nil, String
Resolve one level of aliasing for the given action_name
and wish
.
619 620 621 622 623 624 625 626 |
# File 'lib/innate/node.rb', line 619 def find_aliased_view(action_name, wish) aliased_name, aliased_node = ancestral_trait[:alias_view][action_name] return unless aliased_name aliased_node ||= self aliased_node.update_view_mappings aliased_node.find_view(aliased_name, wish) end |
#find_layout(name, wish) ⇒ Array?
allow layouts combined of method and view… hairy :)
Try to find a suitable value for the layout. This may be a template or the name of a method.
If a layout could be found, an Array with two elements is returned, the first indicating the kind of layout (:layout|:view|:method), the second the found value, which may be a String or Symbol.
447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/innate/node.rb', line 447 def find_layout(name, wish) return unless layout = ancestral_trait[:layout] return unless layout = layout.call(name, wish) if layout.respond_to?(:call) if found = to_layout(layout, wish) [:layout, found] elsif found = find_view(layout, wish) [:view, found] elsif found = find_method(layout, []) [:method, found] end end |
#find_method(name, params) ⇒ String, Symbol
Once 1.9 is mainstream we can use Method#parameters to do accurate prediction
We check arity if possible, but will happily dispatch to any method that has default parameters. If you don’t want your method to be responsible for messing up a request you should think twice about the arguments you specify due to limitations in Ruby.
So if you want your method to take only one parameter which may have a default value following will work fine:
def index(foo = "bar", *rest)
But following will respond to /arg1/arg2 and then fail due to ArgumentError:
def index(foo = "bar")
Here a glance at how parameters are expressed in arity:
def index(a) # => 1
def index(a = :a) # => -1
def index(a, *r) # => -2
def index(a = :a, *r) # => -1
def index(a, b) # => 2
def index(a, b, *r) # => -3
def index(a, b = :b) # => -2
def index(a, b = :b, *r) # => -2
def index(a = :a, b = :b) # => -1
def index(a = :a, b = :b, *r) # => -1
501 502 503 504 |
# File 'lib/innate/node.rb', line 501 def find_method(name, params) return unless arity = method_arities[name] name if arity == params.size or arity < 0 end |
#find_provide(path) ⇒ Array
Resolve possible provides for the given path
from #provides.
384 385 386 387 388 389 390 391 392 393 394 395 396 |
# File 'lib/innate/node.rb', line 384 def find_provide(path) pr = provides name, wish, engine = path, 'html', pr['html_handler'] pr.find do |key, value| key = key[/(.*)_handler$/, 1] next unless path =~ /^(.+)\.#{key}$/i name, wish, engine = $1, key, value end return name, wish, engine end |
#find_view(action_name, wish) ⇒ String?
Try to find the best template for the given basename and wish and respect aliased views.
548 549 550 551 552 553 |
# File 'lib/innate/node.rb', line 548 def find_view(action_name, wish) aliased = find_aliased_view(action_name, wish) return aliased if aliased to_view(action_name, wish) end |
#layout(layout_name = nil, &block) ⇒ Proc, String
Define a layout to use on this Node.
A Node can only have one layout, although the template being chosen can depend on #provides.
NOTE:
The behaviour of Node#layout changed significantly from Ramaze, instead
of multitudes of obscure options and methods like deny_layout we simply
take a block and use the returned value as the name for the layout. No
layout will be used if the block returns nil.
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 |
# File 'lib/innate/node.rb', line 665 def layout(layout_name = nil, &block) if layout_name and block # default name, but still check with block trait(:layout => lambda{|name, wish| layout_name.to_s if block.call(name, wish) }) elsif layout_name # name of a method or template trait(:layout => layout_name.to_s) elsif block # call block every request with name and wish, returned value is name # of layout template or method trait(:layout => block) else # remove layout for this node trait(:layout => nil) end return ancestral_trait[:layout] end |
#layout_mappings ⇒ Array<String>+
Combine Innate.options.layouts with either the ‘ancestral_trait` or the #mapping if the trait yields an empty Array.
934 935 936 937 938 939 |
# File 'lib/innate/node.rb', line 934 def layout_mappings paths = [*ancestral_trait[:layouts]] paths = ['/'] if paths.empty? [[*.layouts].flatten, [*paths].flatten] end |
#map(location) ⇒ Object
Shortcut to map or remap this Node.
139 140 141 142 |
# File 'lib/innate/node.rb', line 139 def map(location) trait :skip_node_map => true Innate.map(location, self) end |
#map_layouts(*locations) ⇒ Node
Set the paths for lookup below the Innate.options.layouts paths.
921 922 923 924 |
# File 'lib/innate/node.rb', line 921 def map_layouts(*locations) trait :layouts => locations.flatten.uniq self end |
#map_views(*locations) ⇒ Node
Set the paths for lookup below the Innate.options.views paths.
890 891 892 893 |
# File 'lib/innate/node.rb', line 890 def map_views(*locations) trait :views => locations.flatten.uniq self end |
#mapping ⇒ String
Tries to find the relative url that this Innate::Node is mapped to. If it cannot find one it will instead generate one based on the snake_cased name of itself.
110 111 112 |
# File 'lib/innate/node.rb', line 110 def mapping Innate.to(self) end |
#needs_method? ⇒ true, false
Whether an Action can be built without a method.
The default is to allow actions that use only a view template, but you might want to turn this on, for example if you have partials in your view directories.
966 967 968 |
# File 'lib/innate/node.rb', line 966 def needs_method? ancestral_trait[:needs_method] end |
#options ⇒ Object
941 942 943 |
# File 'lib/innate/node.rb', line 941 def Innate. end |
#patterns_for(path) ⇒ Action
The innate beauty in Nitro, Ramaze, and Innate.
Will yield the name of the action and parameter for the action method in order of significance.
def foo__bar # responds to /foo/bar
def foo(bar) # also responds to /foo/bar
But foo__bar takes precedence because it’s more explicit.
The last fallback will always be the index action with all of the path turned into parameters.
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 |
# File 'lib/innate/node.rb', line 722 def patterns_for(path) atoms = path.split('/') atoms.delete('') result = nil atoms.size.downto(0) do |len| action_name = atoms[0...len].join('__') params = atoms[len..-1] action_name = 'index' if action_name.empty? and params != ['index'] return result if result = yield(action_name, params) end return nil end |
#possible_exts_for(wish) ⇒ Array
Answer with an array of possible extensions in order of significance for the given wish
.
852 853 854 855 856 857 858 |
# File 'lib/innate/node.rb', line 852 def possible_exts_for(wish) pr = provides return unless engine = pr["#{wish}_handler"] View.exts_of(engine).map{|e_ext| [[*wish].map{|w_ext| /#{w_ext}\.#{e_ext}$/ }, /#{e_ext}$/] }.flatten end |
#possible_paths_for(mappings) ⇒ Array
Answer with an array of possible paths in order of significance for template lookup of the given mappings
.
835 836 837 838 839 840 |
# File 'lib/innate/node.rb', line 835 def possible_paths_for(mappings) root_mappings.map{|root| mappings.first.map{|inner| mappings.last.map{|outer| ::File.join(root, inner, outer, '/') }}}.flatten end |
#provide(format, param = {}, &block) ⇒ Object
The comment of this method may be too short for the effects it has on the rest of Innate, if you feel something is missing please let me know.
Specify which way contents are provided and processed.
Use this to set a templating engine, custom Content-Type, or pass a block to take over the processing of the Action and template yourself.
Provides set via this method will be inherited into subclasses.
The format
is extracted from the PATH_INFO, it simply represents the last extension name in the path.
The provide also has influence on the chosen templates for the Action.
Given a request to ‘/list.rss` the template lookup first tries to find `list.rss.erb`, if that fails it falls back to `list.erb`. If neither of these are available it will try to use the return value of the method in the Action as template.
A request to ‘/list.yaml` would match the format ’yaml’
213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/innate/node.rb', line 213 def provide(format, param = {}, &block) if param.respond_to?(:to_hash) param = param.to_hash handler = block || View.get(param[:engine]) content_type = param[:type] else handler = View.get(param) end raise(ArgumentError, "Need an engine or block") unless handler trait("#{format}_handler" => handler, :provide_set => true) trait("#{format}_content_type" => content_type) if content_type end |
#provide_set? ⇒ true, false
This will return true if the only provides set are by Node::included.
The reasoning behind this is to determine whether the user has touched the provides at all, in which case we will not override the provides in subclasses.
981 982 983 |
# File 'lib/innate/node.rb', line 981 def provide_set? ancestral_trait[:provide_set] end |
#provides ⇒ Object
228 229 230 |
# File 'lib/innate/node.rb', line 228 def provides ancestral_trait.reject{|key, value| key !~ /_handler$/ } end |
#resolve(path) ⇒ nil, Action
Let’s get down to business, first check if we got any wishes regarding the representation from the client, otherwise we will assume he wants html.
361 362 363 364 365 366 367 368 369 370 371 372 373 |
# File 'lib/innate/node.rb', line 361 def resolve(path) name, wish, engine = find_provide(path) node = (respond_to?(:ancestors) && respond_to?(:new)) ? self : self.class action = Action.create(:node => node, :wish => wish, :engine => engine, :path => path) if content_type = node.ancestral_trait["#{wish}_content_type"] action. = {:content_type => content_type} end node.update_method_arities node.update_template_mappings node.fill_action(action, name) end |
#root_mappings ⇒ Array
make sure this is an Array and a new instance so modification on the wrapping array doesn’t affect the original option. [*arr].object_id == arr.object_id if arr is an Array
875 876 877 |
# File 'lib/innate/node.rb', line 875 def root_mappings [*.roots].flatten end |
#to_layout(action_name, wish) ⇒ nil, String
Find the best matching action_name for the layout, if any.
This is mostly an abstract method that you might find handy if you want to do vastly different layout lookup.
641 642 643 644 |
# File 'lib/innate/node.rb', line 641 def to_layout(action_name, wish) return unless files = layout_templates[wish.to_s] files[action_name.to_s] end |
#to_template(path, wish) ⇒ nil, String
Try to find a template at the given path
for wish
.
Since Innate supports multiple paths to templates the path
has to be an Array that may be nested one level.
778 779 780 |
# File 'lib/innate/node.rb', line 778 def to_template(path, wish) to_view(path, wish) || to_layout(path, wish) end |
#to_view(action_name, wish) ⇒ String?
Try to find the best template for the given basename and wish.
This method is mostly here for symetry with #to_layout and to allow you overriding the template lookup easily.
569 570 571 572 |
# File 'lib/innate/node.rb', line 569 def to_view(action_name, wish) return unless files = view_templates[wish.to_s] files[action_name.to_s] end |
#try_resolve(path) ⇒ Response
Let’s try to find some valid action for given path
. Otherwise we dispatch to #action_missing.
277 278 279 280 |
# File 'lib/innate/node.rb', line 277 def try_resolve(path) action = resolve(path) action ? action_found(action) : action_missing(path) end |
#update_layout_mappings ⇒ Object
792 793 794 795 |
# File 'lib/innate/node.rb', line 792 def update_layout_mappings paths = possible_paths_for(layout_mappings) @layout_templates = update_mapping_shared(paths) end |
#update_mapping_shared(paths) ⇒ Object
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 |
# File 'lib/innate/node.rb', line 797 def update_mapping_shared(paths) mapping = {} paths.reject!{|path| !File.directory?(path) } provides.each do |wish_key, engine| wish = wish_key[/(.*)_handler/, 1] exts = possible_exts_for(wish) paths.reverse_each do |path| Find.find(path) do |file| exts.each do |ext| next unless file =~ ext case file.sub(path, '').gsub('/', '__') when /^(.*)\.(.*)\.(.*)$/ action_name, wish_ext, engine_ext = $1, $2, $3 when /^(.*)\.(.*)$/ action_name, wish_ext, engine_ext = $1, wish, $2 end mapping[wish_ext] ||= {} mapping[wish_ext][action_name] = file end end end end return mapping end |
#update_method_arities ⇒ Hash
Answer with a hash, keys are method names, values are method arities.
Note that this will be executed once for every request, once we have settled things down a bit more we can switch to update based on Reloader hooks and update once on startup. However, that may cause problems with dynamically created methods, so let’s play it safe for now.
522 523 524 525 526 527 528 529 530 531 532 533 534 535 |
# File 'lib/innate/node.rb', line 522 def update_method_arities @method_arities = {} exposed = ancestors & Helper::EXPOSE.to_a higher = ancestors.select{|ancestor| ancestor < Innate::Node } (higher + exposed).reverse_each do |ancestor| ancestor.public_instance_methods(false).each do |im| @method_arities[im.to_s] = ancestor.instance_method(im).arity end end @method_arities end |
#update_template_mappings ⇒ Object
782 783 784 785 |
# File 'lib/innate/node.rb', line 782 def update_template_mappings update_view_mappings update_layout_mappings end |
#update_view_mappings ⇒ Object
787 788 789 790 |
# File 'lib/innate/node.rb', line 787 def update_view_mappings paths = possible_paths_for(view_mappings) @view_templates = update_mapping_shared(paths) end |
#view_mappings ⇒ Array<String>+
Combine Innate.options.views with either the ‘ancestral_trait` or the #mapping if the trait yields an empty Array.
903 904 905 906 907 908 |
# File 'lib/innate/node.rb', line 903 def view_mappings paths = [*ancestral_trait[:views]] paths = [mapping] if paths.empty? [[*.views].flatten, [*paths].flatten] end |