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/openssl_wrapper.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/setup/spider_setup_wizard.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, ConsoleWizard, ContentUtils, ControllerMixin, ControllerMixins, Create, DataType, DataTypes, Dispatcher, EventSource, FirstResponder, Fork, GetText, HTML, HTTP, HashDottedAccess, Helpers, I18n, Inflector, LayoutScene, LessCompiler, Logger, Loggers, Memory, Migrations, Model, OpenSslWrapper, 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, MySQLSetupWizard, OracleSetupWizard, OrderedHash, PageController, PeriodicRunner, Rails, Request, Resource, Response, Router, Sanitizer, SassAppImporter, SassCompiler, Scene, Session, SetupTask, Site, SpiderController, SpiderSetupWizard, Tag, Template, TemplateCache, TemplateCompileError, TestCase, TransientHash, UploadedFile, WhiteListSanitizer, Widget, WidgetAttributes, Wizard

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)


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

def apps
  @apps
end

.apps_by_pathHash (readonly)

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

Returns:

  • (Hash)


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

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)


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

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:



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

def home
  @home
end

.loggerSpider::Logger (readonly)

An instance of the shared logger.

Returns:



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

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)


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

def paths
  @paths
end

.resource_typesArray (readonly)

Registered resource types

Returns:

  • (Array)


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

def resource_types
  @resource_types
end

.runmodeString

The current runmode (test, devel or production).

Returns:



51
52
53
# File 'lib/spiderfw/spider.rb', line 51

def runmode
  @runmode
end

.siteSite

Main site

Returns:



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

def site
  @site
end

.spawnerObject

Returns the value of attribute spawner.



75
76
77
# File 'lib/spiderfw/spider.rb', line 75

def spawner
  @spawner
end

Class Method Details

._test_setupObject



1231
1232
1233
1234
1235
# File 'lib/spiderfw/spider.rb', line 1231

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

._test_teardownObject



1237
1238
1239
1240
1241
# File 'lib/spiderfw/spider.rb', line 1237

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



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

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:



660
661
662
663
664
# File 'lib/spiderfw/spider.rb', line 660

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



373
374
375
376
377
378
379
# File 'lib/spiderfw/spider.rb', line 373

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:

Returns:

  • (bool)

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



668
669
670
671
672
# File 'lib/spiderfw/spider.rb', line 668

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



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

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.



719
720
721
722
723
724
725
726
727
# File 'lib/spiderfw/spider.rb', line 719

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

.check_clear_cachesObject



423
424
425
426
427
428
429
430
431
432
# File 'lib/spiderfw/spider.rb', line 423

def check_clear_caches
    if File.exists?(Spider.paths[:clear_file])
        stat = File.stat(Spider.paths[:clear_file])
        last_reset_file = File.join(Spider.paths[:var], 'cache_cleared')
        last_stat = File.exists?(last_reset_file) ? File.stat(last_reset_file) : nil
        if !last_stat || stat.mtime > last_stat.mtime
            Spider.clear_caches!
        end
    end
end

.clear_caches!Object



434
435
436
437
438
439
440
441
442
# File 'lib/spiderfw/spider.rb', line 434

def clear_caches!
    Spider.logger.info("Clearing caches")
    FileUtils.touch(File.join(Spider.paths[:var], 'cache_cleared'))
    Dir.new(Spider::Layout.compiled_folder_path).each do |entry|
        next if ['.', '..'].include?(entry)
        ::FileUtils.rm_rf(File.join(Spider::Layout.compiled_folder_path, entry))
    end
    FileUtils.rm_rf(Spider::Template.cache_path)
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:



766
767
768
769
# File 'lib/spiderfw/spider.rb', line 766

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.



418
419
420
# File 'lib/spiderfw/spider.rb', line 418

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



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

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.



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

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:

Returns:

  • (Array)

    An Array of apps found at path name



565
566
567
568
569
570
571
572
# File 'lib/spiderfw/spider.rb', line 565

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:

Returns:

  • (Array)

    An array of all apps found inside path



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/spiderfw/spider.rb', line 641

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:



851
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
878
879
880
881
882
883
884
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
913
914
915
916
917
918
919
920
# File 'lib/spiderfw/spider.rb', line 851

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



995
996
997
998
# File 'lib/spiderfw/spider.rb', line 995

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



681
682
683
684
685
686
687
688
689
690
691
692
693
# File 'lib/spiderfw/spider.rb', line 681

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:



1221
1222
1223
# File 'lib/spiderfw/spider.rb', line 1221

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.



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

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.



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

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(mod.base_path, 'po', "#{mod.short_name}.pot")
        home_locale = File.join(mod.base_path, '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.



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
168
169
170
171
# File 'lib/spiderfw/spider.rb', line 139

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
    load_configuration File.join($SPIDER_PATH, 'config')
    begin
        user_rc = File.join(Etc.getpwuid.dir, '.spider.conf.yml')
        if File.file?(user_rc)
            load_configuration_file(user_rc)
        end
    rescue NoMethodError # No getpwuid under windows
    end
    load_configuration File.join(@root, 'config')
    self.runmode = $SPIDER_RUNMODE || 'devel'
    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)



1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
# File 'lib/spiderfw/spider.rb', line 1104

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



131
132
133
# File 'lib/spiderfw/spider.rb', line 131

def init_done?
    @init_done
end

.init_pry_debugvoid

This method returns an undefined value.

Inits the pry debugger



1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
# File 'lib/spiderfw/spider.rb', line 1119

def init_pry_debug
    begin
        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"
        Pry::Commands.alias_command "c", "continue"
        Pry::Commands.alias_command "n", "next"
        Pry::Commands.alias_command "s", "step"
        begin
            case RUBY_VERSION
                when /2/
                    require 'byebug'
                else
                    require 'ruby-debug'
            end
        rescue
            require 'debugger'
        end
        case RUBY_VERSION
            when /2/
                if File.exists?(File.join($SPIDER_RUN_PATH,'tmp', 'debug.txt'))
                    Byebug.wait_connection = true
                    Byebug.start
                else
                    Byebug.start
                end
            else
                if File.exists?(File.join($SPIDER_RUN_PATH,'tmp', 'debug.txt'))
                    Debugger.wait_connection = true
                    Debugger.start_remote
                else
                    Debugger.start
                end
        end
    rescue LoadError, RuntimeError => exc
        msg = _('Unable to start debugger. Ensure ruby-debug or byebug is installed (or set debugger.start to false).')
        Spider.output(exc.message)
        Spider.output(msg)
    end
end

.init_ruby_debugvoid

This method returns an undefined value.

Inits ruby-debug



1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
# File 'lib/spiderfw/spider.rb', line 1167

def init_ruby_debug
    begin
        begin
            case RUBY_VERSION
                when /2/
                    require 'byebug'
                else
                    require 'ruby-debug'
            end
  rescue
            require 'debugger'
  end
        case RUBY_VERSION
            when /2/
                if File.exists?(File.join($SPIDER_RUN_PATH,'tmp', 'debug.txt'))
                    Byebug.wait_connection = true
                    Byebug.start
                else
                    Byebug.start
                end
            else
                if File.exists?(File.join($SPIDER_RUN_PATH,'tmp', 'debug.txt'))
                    Debugger.wait_connection = true
                    Debugger.start_remote
                else
                    Debugger.start
                end
        end
    rescue LoadError, RuntimeError => exc
        msg = _('Unable to start debugger. Ensure ruby-debug or byebug 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



1244
1245
1246
# File 'lib/spiderfw/spider.rb', line 1244

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



958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
# File 'lib/spiderfw/spider.rb', line 958

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)



615
616
617
618
619
# File 'lib/spiderfw/spider.rb', line 615

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:



577
578
579
580
581
582
# File 'lib/spiderfw/spider.rb', line 577

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:



587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/spiderfw/spider.rb', line 587

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:



604
605
606
607
608
609
610
611
# File 'lib/spiderfw/spider.rb', line 604

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:



733
734
735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/spiderfw/spider.rb', line 733

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



751
752
753
754
755
756
757
758
759
760
761
762
# File 'lib/spiderfw/spider.rb', line 751

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



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/spiderfw/spider.rb', line 1203

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(Spider.conf.get('i18n.default_locale'))
    end
end

.locale=(val) ⇒ Object



1215
1216
1217
# File 'lib/spiderfw/spider.rb', line 1215

def locale=(val)
    Locale.current = Locale::Tag.parse(val)
end

.main_process_shutdownvoid

This method returns an undefined value.

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



392
393
394
395
396
397
398
399
# File 'lib/spiderfw/spider.rb', line 392

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.



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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/spiderfw/spider.rb', line 225

def main_process_startup
    if RUBY_VERSION =~ /1.8/
        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
    else #VERSIONI > 1.8.7
        if defined?(Listen)
            listener = Listen.to(Spider.paths[:tmp], { :only => /restart.txt$/ } ) { |modified, added, removed|

                unless modified.blank?
                    Process.kill 'HUP', $$
                end
                unless added.blank?
                    Process.kill 'HUP', $$
                end
            }
            @celluloid_thread = Celluloid::Thread.new do 
                listener.start
            end
        else
            Spider.output("Listen gem not installed, unable to monitor restart.txt")
        end
    end

    Signal.trap("TERM") do
        Spider.main_process_shutdown
        exit
    end
    Signal.trap("INT") do
        Spider.main_process_shutdown
        exit
    end
    unless RUBY_PLATFORM =~ /win32|mingw32/
        Signal.trap("HUP") do
            Spider.respawn!
        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

.multithread?Boolean

Returns:

  • (Boolean)


444
445
446
447
# File 'lib/spiderfw/spider.rb', line 444

def multithread?
    return false if $SPIDER_SINGLE_THREADED || Spider.current[:multithread] == false
    return true
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.



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

def mutex_requests!
    @request_mutex = Mutex.new
end

.on_main_process_shutdown(&block) ⇒ Proc

Returns The passed proc.

Parameters:

Returns:

  • (Proc)

    The passed proc



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

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



304
305
306
307
# File 'lib/spiderfw/spider.rb', line 304

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



316
317
318
319
# File 'lib/spiderfw/spider.rb', line 316

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



1252
1253
1254
1255
1256
1257
1258
1259
1260
# File 'lib/spiderfw/spider.rb', line 1252

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:



815
816
817
# File 'lib/spiderfw/spider.rb', line 815

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: {})


805
806
807
808
809
810
# File 'lib/spiderfw/spider.rb', line 805

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

.relative_pathString

Returns ‘/spider’.

Returns:



820
821
822
# File 'lib/spiderfw/spider.rb', line 820

def relative_path
    '/spider'
end

.relovoid

This method returns an undefined value.

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



1033
1034
1035
1036
1037
1038
# File 'lib/spiderfw/spider.rb', line 1033

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



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

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



384
385
386
387
388
# File 'lib/spiderfw/spider.rb', line 384

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.



460
461
462
463
464
# File 'lib/spiderfw/spider.rb', line 460

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



474
475
476
# File 'lib/spiderfw/spider.rb', line 474

def request_mutex
    @request_mutex
end

.request_mutex=(val) ⇒ Mutex

Sets the current Request Mutex

Parameters:

  • (Mutex)

Returns:

  • (Mutex)


481
482
483
# File 'lib/spiderfw/spider.rb', line 481

def request_mutex=(val)
    @request_mutex = val
end

.request_startedvoid

This method returns an undefined value.

Called when a new request is started.



451
452
453
454
455
456
# File 'lib/spiderfw/spider.rb', line 451

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



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
# File 'lib/spiderfw/spider.rb', line 925

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.

chiamato al touch tmp/restart in produzione Terminates the current process and starts a new one



1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# File 'lib/spiderfw/spider.rb', line 1062

def respawn!
    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



413
414
415
# File 'lib/spiderfw/spider.rb', line 413

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.



774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
# File 'lib/spiderfw/spider.rb', line 774

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’, ‘var/data’ and ‘var/sessions’



176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/spiderfw/spider.rb', line 176

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'))
    #nuove cartelle aggiunte
    FileUtils.mkdir_p(Spider.paths[:data])
    FileUtils.mkdir_p(File.join(Spider.paths[:var], 'sessions'))

end

.setup_paths(root) ⇒ Hash

Sets the default paths (see paths).

Returns:

  • (Hash)

    The paths Hash



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/spiderfw/spider.rb', line 522

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[:clear_file] = File.join(@paths[:tmp], 'clear.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.



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/spiderfw/spider.rb', line 323

def shutdown(force=false)
    #Byebug.stop unless defined?(Byebug).blank?
    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
    
    case RUBY_VERSION
        when /2/
            Byebug.post_mortem = false if Object.const_defined?(:Debugger) && Byebug.post_mortem?
        else
            Debugger.post_mortem = false if Object.const_defined?(:Debugger) && Debugger.post_mortem?
    end
    @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



365
366
367
# File 'lib/spiderfw/spider.rb', line 365

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:



1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
# File 'lib/spiderfw/spider.rb', line 1009

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)


489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/spiderfw/spider.rb', line 489

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.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/spiderfw/spider.rb', line 193

def startup
    init
    setup_env
    if Spider.conf.get('template.cache.reload_on_restart')
        FileUtils.touch("#{Spider.paths[:tmp]}/templates_reload.txt")
    end
    check_clear_caches
    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)
        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



310
311
312
# File 'lib/spiderfw/spider.rb', line 310

def startup_done?
    @startup_done
end

.test_setupObject



1225
1226
# File 'lib/spiderfw/spider.rb', line 1225

def test_setup
end

.test_teardownObject



1228
1229
# File 'lib/spiderfw/spider.rb', line 1228

def test_teardown
end

Instance Method Details

#first_found(extensions, path) ⇒ Object



854
855
856
857
858
859
860
861
# File 'lib/spiderfw/spider.rb', line 854

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