Module: Spider

Defined in:
lib/spiderfw/spider.rb,
lib/spiderfw/app.rb,
lib/spiderfw/home.rb,
lib/spiderfw/site.rb,
lib/spiderfw/test.rb,
lib/spiderfw/create.rb,
lib/spiderfw/cmd/cmd.rb,
lib/spiderfw/tag/tag.rb,
lib/spiderfw/version.rb,
lib/spiderfw/autoload.rb,
lib/spiderfw/resource.rb,
lib/spiderfw/http/http.rb,
lib/spiderfw/i18n/cldr.rb,
lib/spiderfw/i18n/i18n.rb,
lib/spiderfw/test/unit.rb,
lib/spiderfw/i18n/rails.rb,
lib/spiderfw/model/sync.rb,
lib/spiderfw/model/type.rb,
lib/spiderfw/utils/fork.rb,
lib/spiderfw/utils/gems.rb,
lib/spiderfw/http/server.rb,
lib/spiderfw/model/model.rb,
lib/spiderfw/model/query.rb,
lib/spiderfw/utils/rails.rb,
lib/spiderfw/i18n/gettext.rb,
lib/spiderfw/utils/logger.rb,
lib/spiderfw/utils/memory.rb,
lib/spiderfw/content_utils.rb,
lib/spiderfw/i18n/provider.rb,
lib/spiderfw/model/element.rb,
lib/spiderfw/model/request.rb,
lib/spiderfw/model/storage.rb,
lib/spiderfw/widget/widget.rb,
lib/spiderfw/model/junction.rb,
lib/spiderfw/model/condition.rb,
lib/spiderfw/model/data_type.rb,
lib/spiderfw/model/datatypes.rb,
lib/spiderfw/model/query_set.rb,
lib/spiderfw/utils/inflector.rb,
lib/spiderfw/utils/profiling.rb,
lib/spiderfw/utils/rails_app.rb,
lib/spiderfw/utils/sanitizer.rb,
lib/spiderfw/controller/scene.rb,
lib/spiderfw/model/base_model.rb,
lib/spiderfw/model/migrations.rb,
lib/spiderfw/model/model_hash.rb,
lib/spiderfw/setup/setup_task.rb,
lib/spiderfw/templates/layout.rb,
lib/spiderfw/test/page_object.rb,
lib/spiderfw/controller/cookie.rb,
lib/spiderfw/controller/router.rb,
lib/spiderfw/http/adapters/cgi.rb,
lib/spiderfw/i18n/shtml_parser.rb,
lib/spiderfw/model/mixins/list.rb,
lib/spiderfw/model/mixins/tree.rb,
lib/spiderfw/model/proxy_model.rb,
lib/spiderfw/model/query_funcs.rb,
lib/spiderfw/model/query_funcs.rb,
lib/spiderfw/setup/app_manager.rb,
lib/spiderfw/utils/http_client.rb,
lib/spiderfw/widget/rest_model.rb,
lib/spiderfw/controller/cookies.rb,
lib/spiderfw/controller/request.rb,
lib/spiderfw/controller/session.rb,
lib/spiderfw/http/adapters/fcgi.rb,
lib/spiderfw/http/adapters/rack.rb,
lib/spiderfw/http/adapters/thin.rb,
lib/spiderfw/model/datatypes/pk.rb,
lib/spiderfw/model/inline_model.rb,
lib/spiderfw/model/unit_of_work.rb,
lib/spiderfw/templates/template.rb,
lib/spiderfw/utils/ordered_hash.rb,
lib/spiderfw/utils/shared_store.rb,
lib/spiderfw/config/configurable.rb,
lib/spiderfw/controller/response.rb,
lib/spiderfw/model/active_record.rb,
lib/spiderfw/model/mixins/mixins.rb,
lib/spiderfw/model/storage/db/db.rb,
lib/spiderfw/templates/blocks/if.rb,
lib/spiderfw/utils/secure_random.rb,
lib/spiderfw/cache/template_cache.rb,
lib/spiderfw/config/configuration.rb,
lib/spiderfw/model/datatypes/bool.rb,
lib/spiderfw/model/datatypes/text.rb,
lib/spiderfw/model/datatypes/uuid.rb,
lib/spiderfw/model/mappers/mapper.rb,
lib/spiderfw/model/storage/schema.rb,
lib/spiderfw/templates/blocks/run.rb,
lib/spiderfw/templates/blocks/tag.rb,
lib/spiderfw/widget/widget_plugin.rb,
lib/spiderfw/config/options/spider.rb,
lib/spiderfw/controller/controller.rb,
lib/spiderfw/controller/dispatcher.rb,
lib/spiderfw/http/adapters/mongrel.rb,
lib/spiderfw/http/adapters/webrick.rb,
lib/spiderfw/model/datatypes/email.rb,
lib/spiderfw/model/identity_mapper.rb,
lib/spiderfw/model/mappers/mappers.rb,
lib/spiderfw/templates/blocks/each.rb,
lib/spiderfw/templates/blocks/html.rb,
lib/spiderfw/templates/blocks/pass.rb,
lib/spiderfw/templates/blocks/text.rb,
lib/spiderfw/utils/periodic_runner.rb,
lib/spiderfw/i18n/javascript_parser.rb,
lib/spiderfw/model/datatypes/binary.rb,
lib/spiderfw/model/mixins/converted.rb,
lib/spiderfw/model/mixins/versioned.rb,
lib/spiderfw/templates/blocks/yield.rb,
lib/spiderfw/test/stubs/mapper_stub.rb,
lib/spiderfw/utils/multi_level_hash.rb,
lib/spiderfw/controller/formats/html.rb,
lib/spiderfw/model/datatypes/decimal.rb,
lib/spiderfw/model/mappers/db_mapper.rb,
lib/spiderfw/setup/app_server_client.rb,
lib/spiderfw/templates/blocks/lambda.rb,
lib/spiderfw/templates/blocks/output.rb,
lib/spiderfw/templates/blocks/render.rb,
lib/spiderfw/templates/blocks/tag_if.rb,
lib/spiderfw/templates/blocks/widget.rb,
lib/spiderfw/test/stubs/storage_stub.rb,
lib/spiderfw/controller/controller_io.rb,
lib/spiderfw/controller/mixins/visual.rb,
lib/spiderfw/model/datatypes/password.rb,
lib/spiderfw/model/integrated_element.rb,
lib/spiderfw/model/migrations/replace.rb,
lib/spiderfw/templates/blocks/attr_if.rb,
lib/spiderfw/templates/blocks/comment.rb,
lib/spiderfw/templates/blocks/recurse.rb,
lib/spiderfw/templates/resources/less.rb,
lib/spiderfw/widget/widget_attributes.rb,
lib/spiderfw/model/datatypes/file_path.rb,
lib/spiderfw/model/datatypes/time_span.rb,
lib/spiderfw/model/mappers/hash_mapper.rb,
lib/spiderfw/model/mixins/synchronized.rb,
lib/spiderfw/templates/blocks/debugger.rb,
lib/spiderfw/templates/template_blocks.rb,
lib/spiderfw/utils/events/event_source.rb,
lib/spiderfw/controller/first_responder.rb,
lib/spiderfw/controller/home_controller.rb,
lib/spiderfw/controller/http_controller.rb,
lib/spiderfw/controller/page_controller.rb,
lib/spiderfw/model/mappers/proxy_mapper.rb,
lib/spiderfw/model/migrations/migration.rb,
lib/spiderfw/model/mixins/state_machine.rb,
lib/spiderfw/model/storage/base_storage.rb,
lib/spiderfw/model/storage/db/db_schema.rb,
lib/spiderfw/model/storage/db/reflector.rb,
lib/spiderfw/model/storage/null_storage.rb,
lib/spiderfw/test/extensions/db_storage.rb,
lib/spiderfw/config/configuration_editor.rb,
lib/spiderfw/controller/controller_mixin.rb,
lib/spiderfw/model/migrations/drop_table.rb,
lib/spiderfw/model/storage/db/db_storage.rb,
lib/spiderfw/controller/mixins/http_mixin.rb,
lib/spiderfw/controller/spider_controller.rb,
lib/spiderfw/templates/blocks/layout_meta.rb,
lib/spiderfw/templates/blocks/text_domain.rb,
lib/spiderfw/controller/session/flash_hash.rb,
lib/spiderfw/model/extended_models/managed.rb,
lib/spiderfw/model/mappers/document_mapper.rb,
lib/spiderfw/model/migrations/drop_element.rb,
lib/spiderfw/model/storage/connection_pool.rb,
lib/spiderfw/model/storage/db/db_connector.rb,
lib/spiderfw/templates/blocks/layout_assets.rb,
lib/spiderfw/controller/session/file_session.rb,
lib/spiderfw/model/migrations/previous_model.rb,
lib/spiderfw/model/migrations/rename_element.rb,
lib/spiderfw/model/storage/db/adapters/mssql.rb,
lib/spiderfw/model/storage/db/adapters/mysql.rb,
lib/spiderfw/model/storage/document/document.rb,
lib/spiderfw/templates/blocks/parent_context.rb,
lib/spiderfw/controller/controller_exceptions.rb,
lib/spiderfw/controller/helpers/widget_helper.rb,
lib/spiderfw/controller/mixins/static_content.rb,
lib/spiderfw/model/storage/db/adapters/oracle.rb,
lib/spiderfw/model/storage/db/adapters/sqlite.rb,
lib/spiderfw/model/storage/db/connectors/jdbc.rb,
lib/spiderfw/model/storage/db/connectors/oci8.rb,
lib/spiderfw/model/storage/db/connectors/odbc.rb,
lib/spiderfw/controller/session/memory_session.rb,
lib/spiderfw/controller/session/transient_hash.rb,
lib/spiderfw/model/datatypes/serialized_object.rb,
lib/spiderfw/utils/loggers/apache_commons_logger.rb,
lib/spiderfw/utils/shared_store/file_shared_store.rb,
lib/spiderfw/utils/shared_store/memory_shared_store.rb,
lib/spiderfw/model/migrations/irreversible_migration.rb,
lib/spiderfw/model/storage/db/connectors/jdbc_oracle.rb,
lib/spiderfw/model/storage/db/dialects/no_total_rows.rb,
lib/spiderfw/model/storage/document/adapters/mongodb.rb,
lib/spiderfw/model/storage/document/document_storage.rb,
lib/spiderfw/templates/resources/sass.rb

Overview

– Modified from: ActiveSupport::OrderedHash, Copyright © 2005 David Heinemeier Hansson

Defined Under Namespace

Modules: App, CommandLine, Configurable, ContentUtils, ControllerMixin, ControllerMixins, Create, DataType, DataTypes, Dispatcher, EventSource, FirstResponder, Fork, GetText, HTML, HTTP, HashDottedAccess, Helpers, I18n, Inflector, LayoutScene, LessCompiler, Logger, Loggers, Memory, Migrations, Model, Profiling, QueryFuncs, RailsApp, RestModel, SecureRandom, Setup, TemplateAssets, TemplateBlocks, Test, Utils, WidgetPlugin, WidgetScene Classes: AppManager, AppServerClient, CompiledTemplate, Configuration, ConfigurationEditor, ConfigurationException, Controller, ControllerIO, Cookie, Cookies, DocType, FileSession, FlashHash, FullSanitizer, HTTPController, Home, HomeController, Layout, LinkSanitizer, MemorySession, MultiLevelHash, OrderedHash, PageController, PeriodicRunner, Rails, Request, Resource, Response, Router, Sanitizer, SassCompiler, Scene, Session, SetupTask, Site, SpiderController, Tag, Template, TemplateCache, TemplateCompileError, TestCase, TransientHash, UploadedFile, WhiteListSanitizer, Widget, WidgetAttributes

Constant Summary collapse

VERSION =
File.read(File.dirname(__FILE__)+'/../../VERSION').strip
Bool =
Spider::DataTypes::Bool
Text =
Spider::DataTypes::Text

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.appsArray (readonly)

An hash of registered Spider::App, indexed by name.

Returns:

  • (Array)


40
41
42
# File 'lib/spiderfw/spider.rb', line 40

def apps
  @apps
end

.apps_by_pathHash (readonly)

An hash of registred Spider::App modules, indexed by path.

Returns:

  • (Hash)


43
44
45
# File 'lib/spiderfw/spider.rb', line 43

def apps_by_path
  @apps_by_path
end

.apps_by_short_nameHash (readonly)

An hash of registred Spider::App modules, indexed by short name (name without namespace).

Returns:

  • (Hash)


46
47
48
# File 'lib/spiderfw/spider.rb', line 46

def apps_by_short_name
  @apps_by_short_name
end

.configurationObject (readonly) Also known as: config, conf

Returns the value of attribute configuration.



344
345
346
# File 'lib/spiderfw/config/configuration.rb', line 344

def configuration
  @configuration
end

.homeSpider::Home (readonly)

Current Home

Returns:



65
66
67
# File 'lib/spiderfw/spider.rb', line 65

def home
  @home
end

.loggerSpider::Logger (readonly)

An instance of the shared logger.

Returns:



37
38
39
# File 'lib/spiderfw/spider.rb', line 37

def logger
  @logger
end

.pathsHash (readonly)

An hash of runtime paths.

:root

The base runtime path.

:apps

Apps folder.

:core_apps

Spider apps folder.

:config

Config folder.

:views

Runtime views folder.

:var

Var folder. Must be writable. Contains cache, logs, and other files written by the server.

:data

Data folder. Holds static and dynamic files. Some subdirs may have to be writable.

:certs

Certificates folder.

:tmp

Temp folder. Must be writable.

:log

Log location.

Returns:

  • (Hash)


62
63
64
# File 'lib/spiderfw/spider.rb', line 62

def paths
  @paths
end

.resource_typesArray (readonly)

Registered resource types

Returns:

  • (Array)


68
69
70
# File 'lib/spiderfw/spider.rb', line 68

def resource_types
  @resource_types
end

.runmodeString

The current runmode (test, devel or production).

Returns:

  • (String)


49
50
51
# File 'lib/spiderfw/spider.rb', line 49

def runmode
  @runmode
end

.siteSite

Main site

Returns:



71
72
73
# File 'lib/spiderfw/spider.rb', line 71

def site
  @site
end

.spawnerObject

Returns the value of attribute spawner.



73
74
75
# File 'lib/spiderfw/spider.rb', line 73

def spawner
  @spawner
end

Class Method Details

._test_setupObject



1100
1101
1102
1103
1104
# File 'lib/spiderfw/spider.rb', line 1100

def _test_setup
    @apps.each do |name, mod|
        mod.test_setup if mod.respond_to?(:test_setup)
    end
end

._test_teardownObject



1106
1107
1108
1109
1110
# File 'lib/spiderfw/spider.rb', line 1106

def _test_teardown
    @apps.each do |name, mod|
        mod.test_teardown if mod.respond_to?(:test_teardown)
    end
end

.activate_apps(apps, specs = nil) ⇒ Object

Used by configuration editor – TODO



624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'lib/spiderfw/spider.rb', line 624

def activate_apps(apps, specs=nil)
    require 'spiderfw/config/configuration_editor'
    init_base
    unless specs
        specs = {}
        Spider.home.apps.each do |k, v|
            specs[k] = v[:spec] if apps.include?(k)
        end
    end
    editor = Spider::ConfigurationEditor.new
    Spider.config.loaded_files.each do |f|
        editor.load(f)
    end
    c_apps = Spider.config.get('apps') || []
    c_apps = (c_apps + apps).uniq
    editor.set('apps', Spider.apps_load_order(c_apps, specs))
    editor.save
end

.add_app(mod) ⇒ void

This method returns an undefined value.

Registers an App with Spider

Parameters:



587
588
589
590
591
# File 'lib/spiderfw/spider.rb', line 587

def add_app(mod)
    @apps[mod.name] = mod
    @apps_by_path[mod.relative_path] = mod
    @apps_by_short_name[mod.short_name] = mod
end

.add_thread(thr) ⇒ void

This method returns an undefined value.

Adds a running thread to the application. The app will wait for running threads when shutting down.

Parameters:

  • thread (Thread)

    to add



328
329
330
331
332
333
334
# File 'lib/spiderfw/spider.rb', line 328

def add_thread(thr)
    @running_threads ||= []
    @threads_mutex ||= Mutex.new
    @threads_mutex.synchronize do
        @running_threads << thr
    end
end

.app?(path_or_name) ⇒ bool

Returns True if there is an app at given path or with given name, False otherwise.

Parameters:

  • path_or_name (String)

Returns:

  • (bool)

    True if there is an app at given path or with given name, False otherwise



595
596
597
598
599
# File 'lib/spiderfw/spider.rb', line 595

def app?(path_or_name)
    return true if @apps_by_path[path_or_name]
    return true if @apps_by_short_name[path_or_name]
    return false
end

.app_pathsArray

Returns paths to look for apps.

Returns:

  • (Array)

    paths to look for apps



469
470
471
472
473
# File 'lib/spiderfw/spider.rb', line 469

def app_paths
    paths = [$SPIDER_PATHS[:core_apps]]
    paths.unshift(@paths[:apps]) if @paths[:apps]
    paths
end

.apps_load_order(apps, specs) ⇒ Array

Returns the order in which to load apps, based on their specs.

Parameters:

  • apps (Array)

    The apps to order

  • specs (Hash)

    A Hash of the apps’ AppSpecs, indexed by app short name

Returns:

  • (Array)

    the order in which to load apps, based on their specs.



646
647
648
649
650
651
652
653
654
# File 'lib/spiderfw/spider.rb', line 646

def apps_load_order(apps, specs)
    # TODO
    require 'spiderfw/app'
    sort = Spider::App::RuntimeSort.new
    apps.each do |a|
        sort.add(specs[a] ? specs[a] : a)
    end
    sort.tsort.reject{ |a| a.nil? }
end

.conf_alias(name, al = nil) ⇒ Object



351
352
353
# File 'lib/spiderfw/config/configuration.rb', line 351

def self.conf_alias(name, al=nil)
    @configuration.conf_alias(name, al)
end

.config_option(*params) ⇒ Object



348
349
350
# File 'lib/spiderfw/config/configuration.rb', line 348

def self.config_option(*params)
    @configuration.config_option(*params)
end

.controllerClass

Returns the default controller Class (SpiderController).

Returns:



693
694
695
696
# File 'lib/spiderfw/spider.rb', line 693

def controller
    require 'spiderfw/controller/spider_controller'
    SpiderController
end

.currentHash

Returns An Hash of data local to the current request.

Returns:

  • (Hash)

    An Hash of data local to the current request.



373
374
375
# File 'lib/spiderfw/spider.rb', line 373

def current
    Spider::Request.current
end

.find_all_apps(paths = nil) ⇒ Array

Returns An Array of paths for all found apps.

Parameters:

  • An (Array)

    Array of paths to look into. Will use app_paths if nil.

Returns:

  • (Array)

    An Array of paths for all found apps



550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/spiderfw/spider.rb', line 550

def find_all_apps(paths=nil)
    paths ||= self.app_paths

    app_paths = []
    Find.find(*paths) do |path|
        if (File.basename(path) == '_init.rb')
            app_paths << File.dirname(path)
            Find.prune
        elsif File.exist?(File.join(path, '_init.rb'))
            app_paths << path
            Find.prune
        end
    end
    return app_paths
end

.find_app(name) ⇒ String|nil

Finds an app by name, looking in paths and paths.

Returns:

  • (String|nil)

    The path of the found app, or nil if it was not found.



477
478
479
480
481
482
483
484
485
486
487
# File 'lib/spiderfw/spider.rb', line 477

def find_app(name)
    path = nil
    app_paths.each do |base|
        test = File.join(base, name)
        if File.exist?(File.join(test, '_init.rb'))
            path = test
            break
        end
    end
    return path
end

.find_apps(name) ⇒ Array

Finds sub-apps (apps inside another one)

Parameters:

  • name (String)

Returns:

  • (Array)

    An Array of apps found at path name



492
493
494
495
496
497
498
499
# File 'lib/spiderfw/spider.rb', line 492

def find_apps(name)
    app_paths.each do |base|
        test = File.join(base, name)
        if File.exist?(test)
            return find_apps_in_folder(test)
        end
    end
end

.find_apps_in_folder(path) ⇒ Array

Returns An array of all apps found inside path.

Parameters:

  • path (String)

Returns:

  • (Array)

    An array of all apps found inside path



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/spiderfw/spider.rb', line 568

def find_apps_in_folder(path)
    return unless File.directory?(path)
    return [path] if File.exist?(File.join(path, '_init.rb'))
    found = []
    Dir.new(path).each do |f|
        next if f[0].chr == '.'
        found_path = File.join(path, f)
        if File.exist?(File.join(found_path, '/_init.rb'))
            found << found_path
        else
            found += find_apps_in_folder(found_path)
        end
    end
    return found
end

.find_resource(resource_type, path, cur_path = nil, owner_classes = nil, search_paths = []) ⇒ Resource

Returns the full path of a resource.

Spider provides the following resources:

  • :views (:filetypes => [‘.shtml’])

  • :js and :css (:path => ‘public’)

Apps can define their own resource types (see register_resource_type).

This method will look for the resource in the runtime root first, than in the app’s :“#resource_type_path”, and finally in the spider’s gem folder.

For example:

find_resource(:views, ‘abc/my_view’, nil, [MyApp]) will look into:

  • /home/views/my_app/abc/my_view.shtml

  • /home/views/apps/my_app/views/abc/my_view.shtml

  • /lib/spider/views/abc/my_view.shtml

Parameters:

  • resource_type (Symbol)
  • path (String)
  • cur_path (String) (defaults to: nil)

    Current path: if set, will be used to resolve relative paths

  • owner_classes (Array) (defaults to: nil)

    An Array of Classes, which must respond to .app (i.e., they must belong to an App). If set, will be used to determine the apps to look into.

  • search_paths (Array) (defaults to: [])

    An Array of additional paths to look inside

Returns:



778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# File 'lib/spiderfw/spider.rb', line 778

def find_resource(resource_type, path, cur_path=nil, owner_classes=nil, search_paths=[])
    owner_classes = [owner_classes] unless owner_classes.is_a?(Enumerable)
    
    def first_found(extensions, path)
        extensions.each do |ext|
            full = path
            full += '.'+ext if ext
            return full if File.file?(full)
        end
        return nil
    end
    
    search_paths ||= []
    owner_classes.each do |owner_class| # FIXME: refactor
        owner_class = nil if owner_class == NilClass
        resource_config = @resource_types[resource_type]
        raise "Unknown resource type #{resource_type}" unless resource_config
        resource_rel_path = resource_config[:path]
        extensions = [nil] + resource_config[:extensions]
        path.strip!
        if (path[0..3] == 'ROOT')
            path.sub!(/^ROOT/, Spider.paths[:root])
            return Resource.new(path, @home)
        elsif (path[0..5] == 'SPIDER')
            path.sub!(/^SPIDER/, $SPIDER_PATH)
            return Resource.new(path, self)
        elsif (cur_path)
            if (path[0..1] == './')
                return Resource.new(first_found(extensions, File.dirname(cur_path)+path[1..-1]), owner_class)
            elsif (path[0..2] == '../')
                return Resource.new(first_found(extensions, File.dirname(File.dirname(cur_path))+path[2..-1]), owner_class)
            end
        end
        app = nil
        path_app = nil
        if (path[0].chr == '/')
            first_part = path[1..-1].split('/')[0]
            Spider.apps_by_path.each do |p, a|
                if path.index(p+'/') == 1 # FIXME: might not be correct
                #if first_part == p
                    path_app = a
                    path = path[p.length+2..-1]
                    break
                end
            end
            app = path_app
        elsif owner_class.is_a?(Spider::Home)
            app = owner_class
        elsif owner_class <= Spider::App || owner_class == Spider
            app = owner_class
        else
            app = owner_class.app if (owner_class && owner_class.app)
        end
        return Resource.new(cur_path+'/'+path, owner_class) if cur_path && File.file?(cur_path+'/'+path) # !app
        raise "Can't find owner app for resource #{path}" unless app
        search_locations = resource_search_locations(resource_type, app)
        search_paths.each do |p|
            p = [p, owner_class] unless p.is_a?(Array)
            search_locations << p
        end
        search_locations.each do |p|
            found = first_found(extensions, p[0]+'/'+path)
            next if found == cur_path
            definer = path_app || p[1]
            return Resource.new(found, definer) if found
        end
    end
    resource_type, path, cur_path=nil, owner_classes=nil, search_paths
    return Resource.new(path)
end

.find_resource_path(resource_type, path, cur_path = nil, owner_classes = nil, search_paths = []) ⇒ String|nil

See also find_resource

Parameters:

  • resource_type (Symbol)
  • path (String)
  • cur_path (String) (defaults to: nil)

    Current path: if set, will be used to resolve relative paths

  • owner_classes (Array) (defaults to: nil)

    An Array of Classes, which must respond to .app (i.e., they must be inside an app). If set, will be used to determine the apps to look into.

  • search_paths (Array) (defaults to: [])

    An Array of additional paths to look inside

Returns:

  • (String|nil)

    the path of the found Resource, or nil if not found



922
923
924
925
# File 'lib/spiderfw/spider.rb', line 922

def find_resource_path(resource_type, path, cur_path=nil, owner_classes=nil, search_paths=[])
    res = find_resource(resource_type, path, cur_path, owner_classes, search_paths)
    return res ? res.path : nil
end

.fork(&proc) ⇒ Object

Calls Spider::Fork.fork



36
37
38
# File 'lib/spiderfw/utils/fork.rb', line 36

def self.fork(&proc)
    Spider::Fork.fork(&proc)
end

.gem_available?(name, *requirements) ⇒ Boolean

TODO: remove when old RubyGems versions are not a problem anymore

Returns:

  • (Boolean)


4
5
6
7
8
9
10
11
12
13
14
# File 'lib/spiderfw/utils/gems.rb', line 4

def self.gem_available?(name, *requirements)
    if Gem::Specification.respond_to?(:find_by_name)
        begin
            Gem::Specification.find_by_name(name, *requirements)
        rescue Gem::LoadError
            return false
        end
    else
        Gem.available?(name, requirements.first)
    end
end

.get_app_deps(apps, options = {}) ⇒ Array

Returns the dependencies for given apps, based on the apps’ spec.

Options accepts:

  • :optional whether to include optional apps in the dependencies

Parameters:

  • An (Arrray)

    Array of App names

  • options (Hash) (defaults to: {})

Returns:

  • (Array)

    The dependencies for the given apps



608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/spiderfw/spider.rb', line 608

def get_app_deps(apps, options={})
    new_apps = apps.clone
    specs = {}
    init_base
    while !new_apps.empty? && curr = new_apps.pop
        raise "Could not find app #{curr}" unless Spider.home.apps[curr]
        spec = Spider.home.apps[curr][:spec]
        specs[curr] = spec
        new_apps += spec.depends.reject{ |app| specs[app] }
        new_apps += spec.depends_optional.reject{ |app| specs[app] } if options[:optional]
    end
    specs.keys
end

.http_clientObject



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/spiderfw/utils/http_client.rb', line 5

def self.http_client
    uri = URI.parse('http://www.test.com')
    proxy = uri.find_proxy
    klass = nil
    if proxy
        proxy_user, proxy_pass = nil
        proxy_user, proxy_pass = proxy.userinfo.split(/:/) if proxy.userinfo
        Net::HTTP::Proxy(proxy.host, proxy.port, proxy_user, proxy_pass)
    else
        Net::HTTP
    end
end

.i18n(l = self.locale) ⇒ Spider::I18n::Provider

Returns A provider for the given locale.

Parameters:

  • (Locale::Tag)

Returns:



1090
1091
1092
# File 'lib/spiderfw/spider.rb', line 1090

def i18n(l = self.locale)
    Spider::I18n.provider(l)
end

.init(force = false) ⇒ Object

Initializes the runtime environment. This method is called when spider is required. Apps may implement an app_init method, that will be called after Spider::init is done.

Parameters:

  • Force (force=false)

    init, even if it is already done.



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/spiderfw/spider.rb', line 79

def init(force=false)
    return if @init_done && !force
    
    init_base(force)
    
    start_loggers

#            @controller = Controller
    @paths[:spider] = $SPIDER_PATH

    if ($SPIDER_CONFIG_SETS)
        $SPIDER_CONFIG_SETS.each{ |set| @configuration.include_set(set) }
    end
    init_file = File.join($SPIDER_RUN_PATH, 'init.rb')
    ENV['BUNDLE_GEMFILE'] ||= File.join($SPIDER_RUN_PATH, 'Gemfile')
    if File.exists?(ENV['BUNDLE_GEMFILE']) && File.exists?(File.join($SPIDER_RUN_PATH, 'Gemfile.lock'))
        require 'bundler/setup' 
    end
    
    if File.exist?(init_file)
        @home.instance_eval(File.read(init_file), init_file)
    end
    
    init_apps
    @init_done=true
end

.init_appsObject

Sets up GetText for each app, and runs app_init on them, if the app implement it.



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/spiderfw/spider.rb', line 108

def init_apps
    @apps.each do |name, mod|
        repos = []
        if File.directory?(File.join(mod.path, 'po'))
            repos <<  FastGettext::TranslationRepository.build(mod.short_name, :path => File.join(mod.path, 'data', 'locale'))
        end
        home_pot = File.join(Spider.paths[:root], 'po', "#{mod.short_name}.pot")
        home_locale = File.join(Spider.paths[:root], 'data', 'locale')
        if File.file?(home_pot) && File.directory?(home_locale)
            repos << FastGettext::TranslationRepository.build(mod.short_name, :path => home_locale)
        end
        unless repos.empty?
            FastGettext.add_text_domain(mod.short_name, :type => :chain, :chain => repos)
        end
    end
    @apps.each do |name, mod|
        mod.app_init if mod.respond_to?(:app_init)
    end
end

.init_base(force = false) ⇒ Object

Loads configuration, sets up Locale and GetText, sets paths and the default Logger. The runmode is also set at this phase, if it is defined as $SPIDER_RUNMODE or in configuration.

Parameters:

  • Force (force=false)

    init_base, even if it is already done.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/spiderfw/spider.rb', line 137

def init_base(force=false)
    return if @init_base_done && !force
    l = Spider.locale.to_s
    l = $1 if l =~ /(\w\w)_+/
    FastGettext.locale = l
    
    @apps_to_load = []
    @root = $SPIDER_RUN_PATH
    @home = Home.new(@root)
    
    require 'spiderfw/config/options/spider.rb'

    setup_paths(@root)
    all_apps = find_all_apps
    all_apps.each do |path|
        load_configuration(File.join(path, 'config'))
    end
    @runmode = nil
    self.runmode = $SPIDER_RUNMODE if $SPIDER_RUNMODE
    load_configuration File.join($SPIDER_PATH, 'config')
    user_rc = File.join(Etc.getpwuid.dir, '.spider.conf.yml')
    if File.file?(user_rc)
        load_configuration_file(user_rc)
    end
    load_configuration File.join(@root, 'config')
    self.runmode ||= $SPIDER_RUNMODE if $SPIDER_RUNMODE
    Locale.default = Spider.conf.get('i18n.default_locale')
    setup_env
    @logger = Spider::Logger
    @init_base_done = true
end

.init_debugObject

Starts the debugger (ruby-debug, or Pry if debugger.pry configuration is true)



1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
# File 'lib/spiderfw/spider.rb', line 1031

def init_debug
    if Spider.conf.get('debugger.pry')
        begin
            init_pry_debug
        rescue Exception
            init_ruby_debug
        end
    else
        init_ruby_debug
    end
end

.init_done?TrueClass|FalseClass

Returns True if init has already been done.

Returns:

  • (TrueClass|FalseClass)

    True if init has already been done



129
130
131
# File 'lib/spiderfw/spider.rb', line 129

def init_done?
    @init_done
end

.init_pry_debugvoid

This method returns an undefined value.

Inits the pry debugger



1046
1047
1048
1049
1050
1051
1052
1053
1054
# File 'lib/spiderfw/spider.rb', line 1046

def init_pry_debug
    require 'pry'
    require 'pry-nav'
    require 'pry-stack_explorer'
    if File.exists?(File.join($SPIDER_RUN_PATH,'tmp', 'debug.txt'))
        require 'pry-remote'
    end
    Pry::Commands.alias_command "l=", "whereami"
end

.init_ruby_debugvoid

This method returns an undefined value.

Inits ruby-debug



1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
# File 'lib/spiderfw/spider.rb', line 1059

def init_ruby_debug
    begin
        require 'ruby-debug'
        if File.exists?(File.join($SPIDER_RUN_PATH,'tmp', 'debug.txt'))
            Debugger.wait_connection = true
            Debugger.start_remote
        else
            Debugger.start
        end
    rescue LoadError, RuntimeError => exc
        msg = _('Unable to start debugger. Ensure ruby-debug is installed (or set debugger.start to false).')
        Spider.output(exc.message)
        Spider.output(msg)
    end
end

.interactive?bool

Returns True if spider is running in interactive mode (i.e. run from the command line), false otherwise.

Returns:

  • (bool)

    True if spider is running in interactive mode (i.e. run from the command line), false otherwise



1113
1114
1115
# File 'lib/spiderfw/spider.rb', line 1113

def interactive?
    !!$SPIDER_INTERACTIVE
end

.list_resources(resource_type, owner_class = nil, start = nil, search_paths = []) ⇒ Array

Returns an Array of all resources of a certain type

Parameters:

  • resource_type (Symbol)
  • the (owner_class)

    owner of the resource (must respond to .app)

  • start (String) (defaults to: nil)

    A subfolder to start looking from

Returns:

  • (Array)

    An array of resources



885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
# File 'lib/spiderfw/spider.rb', line 885

def list_resources(resource_type, owner_class=nil, start=nil, search_paths = [])
    app = nil
    if owner_class <= Spider::App
        app = owner_class
    else
        app = owner_class.app if (owner_class && owner_class.app)
    end
    search_locations = resource_search_locations(resource_type, app)
    resource_config = @resource_types[resource_type]
    extensions = resource_config[:extensions]
    search_paths.each do |p|
        p = [p, owner_class] unless p.is_a?(Array)
        search_locations << p
    end
    res = []
    search_locations.reverse.each do |p|
        pname = Pathname.new(p[0])
        base = p[0]
        base = File.join(base, start) if start
        extensions.each do |ext|
            Dir.glob(File.join(base, "*.#{ext}")).each do |f|
                res << (Pathname.new(f).relative_path_from(pname)).to_s
            end
        end
    end
    res.uniq
    
end

.load_all_appsvoid

This method returns an undefined value.

Loads all apps inside the defined app paths (see app_paths)



542
543
544
545
546
# File 'lib/spiderfw/spider.rb', line 542

def load_all_apps
    find_all_apps.each do |path|
        load_app_at_path(path)
    end
end

.load_app(name) ⇒ void

This method returns an undefined value.

Loads the given app

Parameters:

  • name (String)


504
505
506
507
508
509
# File 'lib/spiderfw/spider.rb', line 504

def load_app(name)
    paths = find_apps(name)
    paths.each do |path|
        load_app_at_path(path)
    end
end

.load_app_at_path(path) ⇒ void

This method returns an undefined value.

Loads the app inside the give folder

Parameters:

  • path (String)


514
515
516
517
518
519
520
521
522
523
524
525
526
# File 'lib/spiderfw/spider.rb', line 514

def load_app_at_path(path)
    return if @loaded_apps[path]
    relative_path = path
    if Spider.paths[:root] && path.index(Spider.paths[:root])
        home = Pathname.new(Spider.paths[:root])
        pname = Pathname.new(path)
        relative_path = pname.relative_path_from(home).to_s
    end
    @loaded_apps[path] = true
    last_name = File.basename(path)
    app_files = ['_init.rb', last_name+'.rb', 'cmd.rb']
    app_files.each{ |f| require File.join(relative_path, f) if File.exist?(File.join(path, f)) }
end

.load_apps(*l) ⇒ void

This method returns an undefined value.

Loads a list of apps

Parameters:



531
532
533
534
535
536
537
538
# File 'lib/spiderfw/spider.rb', line 531

def load_apps(*l)
    if l.empty?
        l = Spider.conf.get('apps')
    end
    l.each do |app|
        load_app(app)
    end
end

.load_configuration(path) ⇒ void

This method returns an undefined value.

Loads configuration YAML files found inside path

Parameters:

  • path (String)


660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/spiderfw/spider.rb', line 660

def load_configuration(path)
    return unless File.directory?(path)
    opts = File.join(path, 'options.rb')
    require opts if File.exist?(opts)
    Dir.new(path).each do |f|
        f.untaint # FIXME: security parse
        case f
        when /^\./
            next
        when /\.(yaml|yml)$/
            load_configuration_file(File.join(path, f))
        end
    end
end

.load_configuration_file(file) ⇒ void

This method returns an undefined value.

Loads a YAML configuration file

Parameters:

  • path (String)

    to the file



678
679
680
681
682
683
684
685
686
687
688
689
# File 'lib/spiderfw/spider.rb', line 678

def load_configuration_file(file)
    begin
        @configuration.load_yaml(file)
    rescue ConfigurationException => exc
        if exc.type == :yaml
            err = "Configuration file #{path+f} is not valid YAML"
            Spider.output(err, :ERROR)
        else
            raise
        end
    end
end

.localeLocale::Tag

Returns The current locale.

Returns:

  • (Locale::Tag)

    The current locale



1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# File 'lib/spiderfw/spider.rb', line 1076

def locale
    begin
        @current_locale = Locale.current[0]
    rescue
        # There are problems with subsequent requests on Windows, 
        # so use cached locale if Locale.current fails
        l = @current_locale
        l ||= Locale::Tag.parse(Spider.conf.get('locale')) if Spider.conf.get('locale')
        l ||= Locale::Tag.parse('en')
    end
end

.main_process_shutdownvoid

This method returns an undefined value.

Called when the main process is shut down. See also main_process_startup.



347
348
349
350
351
352
353
354
# File 'lib/spiderfw/spider.rb', line 347

def main_process_shutdown
    if startup_done?
        shutdown!
    end
    if @main_process_shutdown_blocks
        @main_process_shutdown_blocks.each{ |b| b.call }
    end
end

.main_process_startupObject

Called before the main process starts up.

This happens, for example, when Spider server is started from command line; the main process can then spawn other processes, as supporting listeners or workers.

Note that in some environments (e.g. Phusion Passenger) there will not be a main process, so this method will not be called.



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/spiderfw/spider.rb', line 219

def main_process_startup
    if defined?(FSSM)
        monitor = FSSM::Monitor.new

        monitor.path(Spider.paths[:tmp], 'restart.txt') do
            create { |base, relative| Process.kill 'HUP', $$ }
            update { |base, relative| Process.kill 'HUP', $$ }            

        end

        if Spider.conf.get('template.cache.use_fssm')
            monitor.path(Spider.paths[:root]) do
                glob '**/*.shtml'
                create { |base, relative| FileUtils.rm_rf(File.join(Spider.paths[:var], 'cache', 'templates')) }
                update { |base, relative| FileUtils.rm_rf(File.join(Spider.paths[:var], 'cache', 'templates')) }                                    
            end
            monitor.path($SPIDER_PATH) do
                glob '**/*.shtml'
                create { |base, relative| FileUtils.rm_rf(File.join(Spider.paths[:var], 'cache', 'templates')) }
                update { |base, relative| FileUtils.rm_rf(File.join(Spider.paths[:var], 'cache', 'templates')) }                                    
            end
            FileUtils.rm_rf(File.join(Spider.paths[:var], 'cache', 'templates'))
        end

        @fssm_thread = Thread.new do
            monitor.run
        end
        Spider.output("Monitoring restart.txt")

    else
        Spider.output("FSSM not installed, unable to monitor restart.txt")
        if Spider.conf.get('template.cache.use_fssm')
            raise "Unable to use FSSM for monitoring templates; use template.cache.disable instead"
        end
    end
    trap('TERM'){ Spider.main_process_shutdown; exit }
    trap('INT'){ Spider.main_process_shutdown; exit }
    trap('HUP'){ Spider.respawn! } unless RUBY_PLATFORM =~ /win32|mingw32/
    
    if @main_process_startup_blocks
        @main_process_startup_blocks.each{ |block| block.call }
    end
    
end

.mutex_requests!void

This method returns an undefined value.

Run a lock around requests, ensuring only one request is run at a time. This is usually not needed, except for testing and special situations.



397
398
399
# File 'lib/spiderfw/spider.rb', line 397

def mutex_requests!
    @request_mutex = Mutex.new
end

.on_main_process_shutdown(&block) ⇒ Proc

Returns The passed proc.

Parameters:

Returns:

  • (Proc)

    The passed proc



358
359
360
361
# File 'lib/spiderfw/spider.rb', line 358

def on_main_process_shutdown(&block)
    @main_process_shutdown_blocks ||= []
    @main_process_shutdown_blocks << block
end

.on_main_process_startup(&proc) ⇒ Proc

Returns The passed proc.

Parameters:

  • proc (Proc)

    A block that will be called when #main_process_startup is run

Returns:

  • (Proc)

    The passed proc



266
267
268
269
# File 'lib/spiderfw/spider.rb', line 266

def on_main_process_startup(&proc)
    @main_process_startup_blocks ||= []
    @main_process_startup_blocks << proc
end

.on_shutdown(&block) ⇒ Proc

Returns The passed proc.

Parameters:

  • proc (Proc)

    A block that will be called when #shutdown is run

Returns:

  • (Proc)

    The passed proc



278
279
280
281
# File 'lib/spiderfw/spider.rb', line 278

def on_shutdown(&block)
    @shutdown_blocks ||= []
    @shutdown_blocks << block
end

.output(str, level = :INFO) ⇒ void

This method returns an undefined value.

Outputs a string, to the console or to log

Parameters:

  • str (String)

    String to output

  • level (Symbol) (defaults to: :INFO)

    Log level



1121
1122
1123
1124
1125
1126
1127
1128
1129
# File 'lib/spiderfw/spider.rb', line 1121

def output(str, level=:INFO)
    use_log = !Spider.interactive? && @logger_started
    if use_log
        @logger.log(level, str)
    else
        str = "#{level}: #{str}" if level == :ERROR
        puts str
    end
end

.pathString

Returns $SPIDER_PATH.

Returns:

  • (String)

    $SPIDER_PATH



742
743
744
# File 'lib/spiderfw/spider.rb', line 742

def path
    $SPIDER_PATH
end

.register_resource_type(name, options = {}) ⇒ void

This method returns an undefined value.

Adds a resource type name must be a symbol, extensions an array of extensions (strings, without the dot) for this resource.

Resources can be searched with find_resource. They will be searched first inside the home, then inside the app’s folder. This way, home can override app resources. See also find_resource.

Options may be:

  • :extensions an Array of possible extensions. If given, find_resource will try appending the extensions

    when looking for the file.
    
  • :path the path of the resource relative to resource root; if not given, name will be used.

Parameters:

  • name (Symbol)
  • options (Hash) (defaults to: {})


732
733
734
735
736
737
# File 'lib/spiderfw/spider.rb', line 732

def register_resource_type(name, options={})
    @resource_types[name] = {
        :extensions => options[:extensions],
        :path => options[:path] || name.to_s
    }
end

.relative_pathString

Returns ‘/spider’.

Returns:

  • (String)

    ‘/spider’



747
748
749
# File 'lib/spiderfw/spider.rb', line 747

def relative_path
    '/spider'
end

.relovoid

This method returns an undefined value.

Reloads all application inside a folder. – TODO: fix or remove



960
961
962
963
964
965
# File 'lib/spiderfw/spider.rb', line 960

def relo
    ad_sources_in_dir(dir)
    self.sources_in_dir(dir).each do |file|
        load(file)
    end
end

.reload_sourcesvoid

This method returns an undefined value.

Reloads all application sources. – TODO: fix or remove



971
972
973
974
975
976
977
978
979
980
981
982
983
984
# File 'lib/spiderfw/spider.rb', line 971

def reload_sources
    logger.debug("Reloading sources")
    crit = Thread.critical
    Thread.critical = true
    $".each do |file|
        if file =~ /^(#{$SPIDER_RUN_PATH}|apps)/ 
         #   logger.debug("RELOADING #{file}")
            load(file)
        else
        #    logger.debug("SKIPPING #{file}")
        end
    end
    Thread.critical = crit
end

.remove_thread(thr) ⇒ void

This method returns an undefined value.

Removes a running thread. See add_thread.

Parameters:

  • The (Thread)

    thread to remove



339
340
341
342
343
# File 'lib/spiderfw/spider.rb', line 339

def remove_thread(thr)
    @threads_mutex.synchronize do
        @running_threads.delete(thr)
    end
end

.request_finishedvoid

This method returns an undefined value.

Called when a new request is finished.



388
389
390
391
392
# File 'lib/spiderfw/spider.rb', line 388

def request_finished
    # Spider.logger.info("Done in #{(Time.now - Spider::Request.current[:_start])*1000}ms")
    Spider::Request.reset_current
    @request_mutex.unlock if (@request_mutex)
end

.request_mutexMutex

Returns The current Request Mutex, if set.

Returns:

  • (Mutex)

    The current Request Mutex, if set



402
403
404
# File 'lib/spiderfw/spider.rb', line 402

def request_mutex
    @request_mutex
end

.request_mutex=(val) ⇒ Mutex

Sets the current Request Mutex

Parameters:

  • (Mutex)

Returns:

  • (Mutex)


409
410
411
# File 'lib/spiderfw/spider.rb', line 409

def request_mutex=(val)
    @request_mutex = val
end

.request_startedvoid

This method returns an undefined value.

Called when a new request is started.



379
380
381
382
383
384
# File 'lib/spiderfw/spider.rb', line 379

def request_started
    @request_mutex.lock if (@request_mutex)
    Spider::Request.current = {
        :_start => Time.now
    }
end

.resource_search_locations(resource_type, app = nil) ⇒ Array

Returns An array of places to look for resources of type resource_type belonging to app.

Parameters:

Returns:

  • (Array)

    An array of places to look for resources of type resource_type belonging to app



852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
# File 'lib/spiderfw/spider.rb', line 852

def resource_search_locations(resource_type, app=nil)
    resource_config = @resource_types[resource_type]
    resource_rel_path = resource_config[:path]
    app_rel_path = app && app.respond_to?(:relative_path) ? app.relative_path : nil
    search_locations = []
    unless Spider.conf.get('resources.disable_custom')
        root_search = File.join(Spider.paths[:root], resource_rel_path)
        root_search = File.join(root_search, app_rel_path) if app_rel_path
        # unless cur_path && cur_path == File.join(root_search, path)
        search_locations = [[root_search, @home]]
        # end
    end
    if app
        if app.respond_to?("#{resource_type}_path")
            search_locations << [app.send("#{resource_type}_path"), app]
        else
            search_locations << [File.join(app.path, resource_rel_path), app]
        end
        if Spider.runmode == 'test'
            search_locations << [File.join(app.path, 'test', resource_rel_path), app]
        end
    end
    spider_path = File.join($SPIDER_PATH, resource_rel_path)
    search_locations << [spider_path, self]
    search_locations
end

.respawn!void

This method returns an undefined value.

Terminates the current process and starts a new one



988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
# File 'lib/spiderfw/spider.rb', line 988

def respawn!
    require 'rbconfig'
    Spider.logger.info("Restarting")
    ruby = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']).sub(/.*\s.*/m, '"\&"')
    Spider.main_process_shutdown
    return if $SPIDER_NO_RESPAWN
    cmd = $SPIDER_SCRIPT || $0
    args = $SPIDER_PROC_ARGS || ARGV
    Spider.logger.debug("CWD: #{Dir.pwd}")
    if RUBY_PLATFORM =~ /win32|mingw32/
        start_cmd = "start cmd /C #{ruby} #{cmd} #{args.join(' ')}"
        Spider.logger.debug(start_cmd)
        IO.popen(start_cmd)
        sleep 5
    else
        start_cmd = "#{ruby} #{cmd} #{args.join(' ')}"
        Spider.logger.debug(start_cmd)
        exec(start_cmd)
    end
end

.restart!void

This method returns an undefined value.

Restarts the application.

Note that this actually touches the restart file (tmp/restart.txt by default), so the same effect can by achieved by manually touching the file



368
369
370
# File 'lib/spiderfw/spider.rb', line 368

def restart!
    FileUtils.touch(@paths[:restart_file])
end

.route_apps(*apps) ⇒ void

This method returns an undefined value.

Sets routes on the controller for the given apps.

Parameters:

  • An (Array)

    array of app names to route.



701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/spiderfw/spider.rb', line 701

def route_apps(*apps)
    options = {}
    if apps[-1].is_a?(Hash)
        options = apps.pop
    end
    @route_apps = apps.empty? ? true : apps
    if (@route_apps)
        apps_to_route = @route_apps == true ? self.apps.values : @route_apps.map{ |name| self.apps[name] }
    end
    if options[:except]
        apps_to_route.reject{ |app| options[:except].include?(app) }
    end
    if (apps_to_route)
        apps_to_route.each{ |app| @home.controller.route_app(app) }
    end
end

.setup_envvoid

This method returns an undefined value.

Creates runtime folders: ‘tmp’, ‘var’, ‘var/memory’ and ‘var/data’



172
173
174
175
176
177
178
179
180
181
# File 'lib/spiderfw/spider.rb', line 172

def setup_env
    unless File.exists?(File.join(Spider.paths[:root], 'init.rb'))
        raise "This command must be run from the root directory"
    end
    FileUtils.mkdir_p(Spider.paths[:tmp])
    FileUtils.mkdir_p(Spider.paths[:var])
    FileUtils.mkdir_p(File.join(Spider.paths[:var], 'memory'))
    FileUtils.mkdir_p(File.join(Spider.paths[:var], 'data'))
    
end

.setup_paths(root) ⇒ Hash

Sets the default paths (see paths).

Returns:

  • (Hash)

    The paths Hash



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/spiderfw/spider.rb', line 450

def setup_paths(root)
    @paths[:root] = root
    @paths[:apps] = File.join(root, 'apps')
    @paths[:core_apps] = $SPIDER_PATHS[:core_apps]
    @paths[:config] = File.join(root, 'config')
    @paths[:layouts] = File.join(root, 'layouts')
    @paths[:var] = File.join(root, 'var')
    @paths[:certs] = File.join(@paths[:config], 'certs')
    @paths[:tmp] = File.join(root, 'tmp')
    @paths[:data] = File.join(root, 'data')
    @paths[:log] = File.join(@paths[:var], 'log')
    @paths[:restart_file] = File.join(@paths[:tmp], 'restart.txt')
    @paths.each do |k, path|
        @paths[k] = File.expand_path(File.readlink(path)) if File.symlink?(path)
    end
    @paths
end

.shutdown(force = false) ⇒ void

This method returns an undefined value.

Invoked when a server is shutdown. Apps may implement the app_shutdown method, that will be called.



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/spiderfw/spider.rb', line 285

def shutdown(force=false)
    unless force
        #return unless Thread.current == Thread.main
        return if @shutdown_done
    end
    @shutdown_done = true
    Spider.logger.debug("Shutdown")
    if @running_threads
        begin
            Timeout.timeout(Spider.conf.get('process.shutdown_timeout')) do
                @running_threads.each do |thr|
                    thr.join if thr.alive?
                end
            end
        rescue => exc
            Spider.logger.error(exc)
            @running_threads.each do |thr|
                begin
                    thr.kill
                rescue => exc
                end
            end
        end
    end
    Debugger.post_mortem = false if Object.const_defined?(:Debugger) && Debugger.post_mortem?
    @apps.each do |name, mod|
        mod.app_shutdown if mod.respond_to?(:app_shutdown)
    end
    if @shutdown_blocks
        @shutdown_blocks.each{ |b| b.call }
    end
end

.shutdown!void

This method returns an undefined value.

Force shutdown, even if it has been done already



320
321
322
# File 'lib/spiderfw/spider.rb', line 320

def shutdown!
    shutdown(true)
end

.sources_in_dir(path) ⇒ void

This method returns an undefined value.

Lists all sources inside a path. – TODO: fix or remove

Parameters:

  • path (String)


936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
# File 'lib/spiderfw/spider.rb', line 936

def sources_in_dir(path)
    loaded = []
    $".each do |file|
        basename = File.basename(file)
        next if (basename == 'spider.rb' || basename == 'options.rb')
        if (file[0..path.length-1] == path)
           loaded.push(file)
        else
            $:.each do |dir|
                file_path = File.join(dir, file)
                if (file_path =~ /^#{path}/)  # FileTest.exists?(file_path) && 
                    loaded.push(file_path)
                end
            end
        end
    end
    return loaded
end

.start_loggers(force = false) ⇒ true

Closes any open loggers, and opens new ones based on configured settings.

Parameters:

  • force (bool) (defaults to: false)

    to start loggers even if already started.

Returns:

  • (true)


417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/spiderfw/spider.rb', line 417

def start_loggers(force=false)
    init_base
    return if @logger_started && !force
    @logger.close_all
    @logger.open(STDERR, Spider.conf.get('log.console')) if Spider.conf.get('log.console')
    begin
        FileUtils.mkdir(@paths[:log]) unless File.exist?(@paths[:log])
    rescue => exc
        @logger.error("Unable to create log folder") if File.exist?(File.dirname(@paths[:log]))
    end
    if @paths[:log] && File.exist?(@paths[:log])
        @logger.open(File.join(@paths[:log], 'error.log'), :ERROR) if Spider.conf.get('log.errors')
        if Spider.conf.get('log.level')
            @logger.open(File.join(@paths[:log], Spider.conf.get('log.file_name')), Spider.conf.get('log.level'))
        end
    end
    if RUBY_PLATFORM =~ /java/ && Spider.conf.get('log.apache_commons')
        begin
            require 'spiderfw/utils/loggers/apache_commons_logger'
            l = Spider::Loggers::ApacheCommonsLogger.new
            @logger.add('apache_commons_logger', l)
        rescue NameError
            $stderr << "Warning: Unable to load Java class org.apache.commons.logging.LogFactory\n"
        end
    end
    $LOG = @logger
    Object.const_set(:LOGGER, @logger)
    @logger_started = true
end

.startupvoid

This method returns an undefined value.

Invoked before a long running service started. Apps may implement the app_startup method, that will be called.



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/spiderfw/spider.rb', line 186

def startup
    init
    setup_env
    if Spider.conf.get('template.cache.reload_on_restart')
        FileUtils.touch("#{Spider.paths[:tmp]}/templates_reload.txt")
    end
    unless Spider.runmode == 'test'
        if domain = Spider.conf.get('site.domain')
            ssl_port = Spider.conf.get('site.ssl') ? Spider.conf.get('site.ssl_port') : nil
            Spider.site = Site.new(domain, Spider.conf.get('site.port'), ssl_port)
        elsif File.exists?(Site.cache_file)
            Spider.site = Site.load_cache
        end
    end
    if Spider.conf.get('request.mutex')
        mutex_requests!
    end
    @apps.each do |name, mod|
        mod.app_startup if mod.respond_to?(:app_startup)
    end
    @startup_done = true
    at_exit do
        Spider.shutdown
    end
end

.startup_done?true

Returns True if startup has been done.

Returns:

  • (true)

    True if startup has been done



272
273
274
# File 'lib/spiderfw/spider.rb', line 272

def startup_done?
    @startup_done
end

.test_setupObject



1094
1095
# File 'lib/spiderfw/spider.rb', line 1094

def test_setup
end

.test_teardownObject



1097
1098
# File 'lib/spiderfw/spider.rb', line 1097

def test_teardown
end

Instance Method Details

#first_found(extensions, path) ⇒ Object



781
782
783
784
785
786
787
788
# File 'lib/spiderfw/spider.rb', line 781

def first_found(extensions, path)
    extensions.each do |ext|
        full = path
        full += '.'+ext if ext
        return full if File.file?(full)
    end
    return nil
end