CombinedText
stringlengths
4
3.42M
require 'rubygems' require 'active_record' module DatabaseHelper database_url = ENV['database_url'] database_url |= 'test' DB_PARAMS = { :adapter => "postgresql", :host => "localhost", :database => "test", :username => "postgres", :password => "test" } ActiveRecord::Base.establish_connection(DB_PARAMS) end Made database_helper.rb more heroku friendly. require 'rubygems' require 'active_record' require 'uri' module DatabaseHelper #DB_PARAMS = {:adapter => "postgresql",:host => "localhost",:database => "test",:username => "postgres",:password => "test"} db = URI.parse(ENV['DATABASE_URL'] || 'postgresql://localhost/test') ActiveRecord::Base.establish_connection( :adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme, :host => db.host, :username => db.user.nil? ? 'postgres' : db.user, :password => db.password.nil? ? 'test' : db.password, :database => db.path[1..-1], :encoding => 'utf8' ) end
require 'sinatra/base' require 'sanitize' module Sinatra module Apps def self.registered(app) app.helpers Apps::Helpers # list all the apps app.get "/api/v1/apps" do list = apps_list(request) json_result(list.to_json) end app.get "/api/v1/app_categories" do data = App.load_apps categories = data.map{|d| d['categories'] }.flatten.compact.uniq.sort list = { :levels => AppParser::LEVELS, :categories => AppParser::CATEGORIES, :extensions => AppParser::EXTENSIONS, :privacy_levels => AppParser::PRIVACY_LEVELS, :app_types => AppParser::APP_TYPES } list.to_json end app.get "/api/v1/app_platforms" do res = [] App.load_apps.each{|a| res += (a['doesnt_work'] || []) + (a['only_works'] || []) } res.uniq.sort.to_json end # single app details app.get "/api/v1/apps/:tool_id" do host = request.scheme + "://" + request.host_with_port return @error unless get_tool json_result(fix_tool(@tool, @tool_summary).to_json) end # list all the reviews for an app app.get "/api/v1/apps/:tool_id/reviews" do host = request.scheme + "://" + request.host_with_port limit = 15 return @error unless get_tool return @error if params[:only_for_token] && !confirm_token return @error if params[:for_current_user] && !confirm_token reviews = AppReview.all(:tool_id => params[:tool_id], :comments.not => nil, :order => [:id.desc]) reviews = reviews.all(:external_access_token_id => @token.id) if params[:only_for_token] reviews = reviews.all(:external_access_token_id => @token.id, :user_name => session[:user_key]) if params[:for_current_user] total = reviews.count offset = params[:offset].to_i found_reviews = reviews.all(:offset => offset, :limit => limit) next_url = total > offset + limit ? (host + "/api/v1/apps/#{params[:tool_id]}/reviews?offset=#{offset+limit}") : nil if params['no_meta'] next_url += "&no_meta=1" if next_url result = found_reviews.map{|r| review_as_json(r) } else result = { :meta => {:next => next_url}, :current_offset => offset, :limit => limit, :objects => found_reviews.map{|r| review_as_json(r) } } end response.headers['Link'] = "<#{next_url}>; rel=\"next\"" if next_url json_result(result.to_json) end app.post "/api/v1/filter" do halt 400, {:error => "Not logged in"}.to_json unless session['user_key'] @filter = AppFilter.first_or_new(:username => "@#{session['user_key']}") @filter.update_settings(params) json_result(@filter.to_json) end # review an app app.post "/api/v1/apps/:tool_id/reviews" do host = request.scheme + "://" + request.host_with_port return @error unless confirm_token && get_tool if @internal_token && key = session[:user_key] params[:user_name] = key params[:user_url] = "https://twitter.com/#{key}" params[:user_id] = key params[:user_avatar_url] = "https://api.twitter.com/1/users/profile_image/#{key}" end required_fields = [:user_name, :user_id, :rating] optional_fields = [:user_avatar_url, :comments, :user_url] required_fields.each do |field| if !params[field] || params[field].empty? return {:message => "The field '#{field}' is required", :type => 'error'}.to_json end end optional_fields.each do |field| params.delete(field) if params[field] && params[field].empty? end review = AppReview.first_or_new(:tool_id => params[:tool_id], :external_access_token_id => @token.id, :user_id => params[:user_id]) review.tool_name = @tool['name'] review.created_at ||= Time.now (required_fields + optional_fields).each do |field| review.send("#{field}=", sanitize(params[field])) if params[field] end review.save! @tool_summary.update_counts json = review_as_json(review) json['app'] = fix_tool(@tool, @tool_summary) json_result(json.to_json) end app.get "/data/app_reviews.atom" do reviews = AppReview.all(:created_at.gt => (Date.today - 60), :order => :id.desc) host = request.scheme + "://" + request.host_with_port headers 'Content-Type' => 'application/atom+xml' xml = <<-XML <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>LTI App Reviews</title> <subtitle>A list of recent reviews of LTI apps</subtitle> <link href="#{host}/data/app_reviews.atom" rel="self" /> <link href="#{host}/" /> <id>urn:uuid:2d6341a0-a046-11e1-a8b1-0800200c9a67</id> <updated>#{Time.now.iso8601}</updated> XML reviews.each do |review| url = "#{host}/tools.html?tool=#{review.tool_id}" xml += <<-XML <entry> <title>#{review.user_name} -- #{review.tool_name}</title> <link href="#{host}/index.html?tool=#{review.tool_id}" /> <id>#{review.id}</id> <updated>#{review.created_at.iso8601}</updated> <summary>#{review.rating} star(s). #{review.comments}</summary> <author> <name>#{ review.user_name }</name> <url>#{ review.user_url }</url> </author> </entry> XML end xml += <<-XML </feed> XML xml end app.get "/data/lti_apps.atom" do data = apps_list(request, false).select{|a| !a['pending'] } host = request.scheme + "://" + request.host_with_port headers 'Content-Type' => 'application/atom+xml' xml = <<-XML <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>LTI Apps</title> <subtitle>A list of known LTI apps</subtitle> <link href="#{host}/data/lti_apps.atom" rel="self" /> <link href="#{host}/" /> <id>urn:uuid:2d6341a0-a046-11e1-a8b1-0800200c9a66</id> <updated>#{Time.now.iso8601}</updated> XML data.each do |app| url = app['data_url'] ? "#{host}/tools.html?tool=#{app['id']}" : "#{host}/index.html?tool=#{app['id']}" xml += <<-XML <entry> <title>#{app['name']}</title> <link href="#{host}/index.html?tool=#{app['id']}" /> <id>#{app['id']}</id> <updated>#{app['added']}</updated> <summary>#{app['description'] || app['short_description']}</summary> <author> <name>LTI Examples</name> </author> </entry> XML end xml += <<-XML </feed> XML xml end end module Helpers def sanitize(raw) Sanitize.clean(raw) end def apps_list(request, paginated=true) host = request.scheme + "://" + request.host_with_port limit = 24 params = request.params offset = params['offset'].to_i filter = AppFilter.first(:code => params['filter']) data = App.load_apps(filter).sort_by{|a| [(0 - (a['uses'] || 0)), a['name'].downcase || 'zzz'] } [['category', 'categories'], ['level', 'levels'], ['extension', 'extensions']].each do |filter, key| if params[filter] && params[filter].length > 0 if params[filter] == 'all' data = data.select{|e| e[key] } else data = data.select{|e| e[key] && e[key].include?(params[filter]) } end end end if params['pending'] if admin? data = App.all(:pending => true).map{|a| a.settings || {}} else data = [] end end if params['recent'] && params['recent'].length > 0 data = data.sort{|a, b| b['added'] <=> a['added'] } cutoff = (Time.now - (60 * 60 * 24 * 7 * 24)).utc.iso8601 recent = data.select{|e| e['added'] > cutoff} if recent.length < 6 data = data[0, 6] else data = recent end end if params['public'] && params['public'].length > 0 data = data.select{|e| (e['app_type'] == 'open_launch' || e['app_type'] == 'data') } end if params['platform'] && params['platform'].length > 0 data = data.select{|e| (!e['doesnt_work'] || !e['doesnt_work'].include?(params['platform'])) && (!e['only_works'] || e['only_works'].include?(params['platform'])) } # if params['platform'] == 'Canvas' # bad_tools = ['titanpad', 'flickr'] # data = data.select{|e| !bad_tools.include?(e['id']) } # else # bad_tools = ['wolfram', 'wiktionary', 'graph_builder'] # data = data.select{|e| !bad_tools.include?(e['id']) } # end end found_data = data if paginated found_data = found_data[offset, limit] end summaries = App.all(:tool_id => found_data.map{|d| d['id'] }) found_data = found_data.map do |tool| summary = summaries.detect{|s| s.tool_id == tool['id'] } fix_tool(tool, summary || false) end if paginated next_url = data.length > offset + limit ? (host + "/api/v1/apps?offset=#{offset + limit}") : nil if next_url ['filter', 'no_meta', 'category', 'level', 'extension', 'recent', 'public', 'platform', 'pending'].each do |key| next_url += "&#{key}=#{CGI.escape(params[key])}" if params[key] end response.headers['Link'] = "<#{next_url}>; rel=\"next\"" end if params['no_meta'] found_data else { :meta => {:next => next_url}, :current_offset => offset, :limit => limit, :objects => found_data } end else data end end def fix_tool(tool, tool_summary) host = request.scheme + "://" + request.host_with_port if tool_summary tool['ratings_count'] = tool_summary.ratings_count tool['comments_count'] = tool_summary.comments_count tool['avg_rating'] = tool_summary.avg_rating end tool['ratings_count'] ||= 0 tool['comments_count'] ||= 0 tool['banner_url'] ||= "/tools/#{tool['id']}/banner.png" tool['logo_url'] ||= "/tools/#{tool['id']}/logo.png" tool['icon_url'] ||= "/tools/#{tool['id']}/icon.png" cutoff = (Time.now - (60 * 60 * 24 * 7 * 24)).utc.iso8601 tool['new'] = tool['added'] && tool['added'] > cutoff tool['config_url'] ||= "/tools/#{tool['id']}/config.xml" if !tool['config_directions'] if tool['app_type'] == 'data' tool['data_url'] ||= "/tools/#{tool['id']}/data.json" tool['extensions'] = ["editor_button", "resource_selection"] tool['any_key'] = true tool['preview'] ||= { "url" => "/tools/public_collections/index.html?tool=#{tool['id']}", "height" => tool['height'] || 475 } elsif tool['app_type'] == 'open_launch' tool['any_key'] = true tool['extensions'] = ["editor_button", "resource_selection"] tool['preview'] ||= { "url" => "/tools/#{tool['id']}/index.html", "height" => tool['height'] || 475 } end ['big_image_url', 'image_url', 'icon_url', 'banner_url', 'logo_url', 'config_url', 'launch_url'].each do |key| tool[key] = prepend_host(tool[key], host) if tool[key] end tool end def prepend_host(path, host) if path.is_a?(Array) return path.map do |elem| elem['url'] = prepend_host(elem['url'], host) elem end end path = host + path if path && path.match(/^\//) path end def json_result(json) if params['callback'] return "#{params['callback']}(#{json})" else return json end end def review_as_json(review) fields = [:id, :user_name, :user_url, :user_avatar_url, :tool_name, :rating, :comments, :source_name, :source_url] res = {} res['created'] = review.created_at.strftime("%b %e, %Y") fields.each do |field| res[field] = review.send(field) end res end def confirm_token if session[:user_key] @token = ExternalAccessToken.first(:name => "LTI-Examples", :active => true) @internal_token = true else @token = ExternalAccessToken.first(:token => params['access_token'], :active => true) end if !@token @error = {:message => "Invalid token", :type => "error"}.to_json false else @token end end def get_tool id = params[:tool_id] @tool_summary = App.first(:tool_id => id ) if @tool_summary && @tool_summary.pending @tool_summary = nil unless admin?(id) end if @tool_summary && @tool_summary.settings @tool = @tool_summary.settings else data = App.load_apps @tool = data.detect{|t| t['id'] == id } @tool_summary = App.first_or_create(:tool_id => @tool['id'] ) if @tool && !@tool['pending'] end if !@tool @error = {:message => "Tool not found", :type => "error"}.to_json false else @tool end end end end register Apps end try large page size Change-Id: I0d4531039d2d76a04aae4c28daae87f4b15f8099 Reviewed-on: https://gerrit.instructure.com/19867 Reviewed-by: Brian Whitmer <760e7dab2836853c63805033e514668301fa9c47@instructure.com> Product-Review: Brian Whitmer <760e7dab2836853c63805033e514668301fa9c47@instructure.com> QA-Review: Brian Whitmer <760e7dab2836853c63805033e514668301fa9c47@instructure.com> Tested-by: Brian Whitmer <760e7dab2836853c63805033e514668301fa9c47@instructure.com> require 'sinatra/base' require 'sanitize' module Sinatra module Apps def self.registered(app) app.helpers Apps::Helpers # list all the apps app.get "/api/v1/apps" do list = apps_list(request) json_result(list.to_json) end app.get "/api/v1/app_categories" do data = App.load_apps categories = data.map{|d| d['categories'] }.flatten.compact.uniq.sort list = { :levels => AppParser::LEVELS, :categories => AppParser::CATEGORIES, :extensions => AppParser::EXTENSIONS, :privacy_levels => AppParser::PRIVACY_LEVELS, :app_types => AppParser::APP_TYPES } list.to_json end app.get "/api/v1/app_platforms" do res = [] App.load_apps.each{|a| res += (a['doesnt_work'] || []) + (a['only_works'] || []) } res.uniq.sort.to_json end # single app details app.get "/api/v1/apps/:tool_id" do host = request.scheme + "://" + request.host_with_port return @error unless get_tool json_result(fix_tool(@tool, @tool_summary).to_json) end # list all the reviews for an app app.get "/api/v1/apps/:tool_id/reviews" do host = request.scheme + "://" + request.host_with_port limit = 15 return @error unless get_tool return @error if params[:only_for_token] && !confirm_token return @error if params[:for_current_user] && !confirm_token reviews = AppReview.all(:tool_id => params[:tool_id], :comments.not => nil, :order => [:id.desc]) reviews = reviews.all(:external_access_token_id => @token.id) if params[:only_for_token] reviews = reviews.all(:external_access_token_id => @token.id, :user_name => session[:user_key]) if params[:for_current_user] total = reviews.count offset = params[:offset].to_i found_reviews = reviews.all(:offset => offset, :limit => limit) next_url = total > offset + limit ? (host + "/api/v1/apps/#{params[:tool_id]}/reviews?offset=#{offset+limit}") : nil if params['no_meta'] next_url += "&no_meta=1" if next_url result = found_reviews.map{|r| review_as_json(r) } else result = { :meta => {:next => next_url}, :current_offset => offset, :limit => limit, :objects => found_reviews.map{|r| review_as_json(r) } } end response.headers['Link'] = "<#{next_url}>; rel=\"next\"" if next_url json_result(result.to_json) end app.post "/api/v1/filter" do halt 400, {:error => "Not logged in"}.to_json unless session['user_key'] @filter = AppFilter.first_or_new(:username => "@#{session['user_key']}") @filter.update_settings(params) json_result(@filter.to_json) end # review an app app.post "/api/v1/apps/:tool_id/reviews" do host = request.scheme + "://" + request.host_with_port return @error unless confirm_token && get_tool if @internal_token && key = session[:user_key] params[:user_name] = key params[:user_url] = "https://twitter.com/#{key}" params[:user_id] = key params[:user_avatar_url] = "https://api.twitter.com/1/users/profile_image/#{key}" end required_fields = [:user_name, :user_id, :rating] optional_fields = [:user_avatar_url, :comments, :user_url] required_fields.each do |field| if !params[field] || params[field].empty? return {:message => "The field '#{field}' is required", :type => 'error'}.to_json end end optional_fields.each do |field| params.delete(field) if params[field] && params[field].empty? end review = AppReview.first_or_new(:tool_id => params[:tool_id], :external_access_token_id => @token.id, :user_id => params[:user_id]) review.tool_name = @tool['name'] review.created_at ||= Time.now (required_fields + optional_fields).each do |field| review.send("#{field}=", sanitize(params[field])) if params[field] end review.save! @tool_summary.update_counts json = review_as_json(review) json['app'] = fix_tool(@tool, @tool_summary) json_result(json.to_json) end app.get "/data/app_reviews.atom" do reviews = AppReview.all(:created_at.gt => (Date.today - 60), :order => :id.desc) host = request.scheme + "://" + request.host_with_port headers 'Content-Type' => 'application/atom+xml' xml = <<-XML <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>LTI App Reviews</title> <subtitle>A list of recent reviews of LTI apps</subtitle> <link href="#{host}/data/app_reviews.atom" rel="self" /> <link href="#{host}/" /> <id>urn:uuid:2d6341a0-a046-11e1-a8b1-0800200c9a67</id> <updated>#{Time.now.iso8601}</updated> XML reviews.each do |review| url = "#{host}/tools.html?tool=#{review.tool_id}" xml += <<-XML <entry> <title>#{review.user_name} -- #{review.tool_name}</title> <link href="#{host}/index.html?tool=#{review.tool_id}" /> <id>#{review.id}</id> <updated>#{review.created_at.iso8601}</updated> <summary>#{review.rating} star(s). #{review.comments}</summary> <author> <name>#{ review.user_name }</name> <url>#{ review.user_url }</url> </author> </entry> XML end xml += <<-XML </feed> XML xml end app.get "/data/lti_apps.atom" do data = apps_list(request, false).select{|a| !a['pending'] } host = request.scheme + "://" + request.host_with_port headers 'Content-Type' => 'application/atom+xml' xml = <<-XML <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>LTI Apps</title> <subtitle>A list of known LTI apps</subtitle> <link href="#{host}/data/lti_apps.atom" rel="self" /> <link href="#{host}/" /> <id>urn:uuid:2d6341a0-a046-11e1-a8b1-0800200c9a66</id> <updated>#{Time.now.iso8601}</updated> XML data.each do |app| url = app['data_url'] ? "#{host}/tools.html?tool=#{app['id']}" : "#{host}/index.html?tool=#{app['id']}" xml += <<-XML <entry> <title>#{app['name']}</title> <link href="#{host}/index.html?tool=#{app['id']}" /> <id>#{app['id']}</id> <updated>#{app['added']}</updated> <summary>#{app['description'] || app['short_description']}</summary> <author> <name>LTI Examples</name> </author> </entry> XML end xml += <<-XML </feed> XML xml end end module Helpers def sanitize(raw) Sanitize.clean(raw) end def apps_list(request, paginated=true) host = request.scheme + "://" + request.host_with_port limit = 72 params = request.params offset = params['offset'].to_i filter = AppFilter.first(:code => params['filter']) data = App.load_apps(filter).sort_by{|a| [(0 - (a['uses'] || 0)), a['name'].downcase || 'zzz'] } [['category', 'categories'], ['level', 'levels'], ['extension', 'extensions']].each do |filter, key| if params[filter] && params[filter].length > 0 if params[filter] == 'all' data = data.select{|e| e[key] } else data = data.select{|e| e[key] && e[key].include?(params[filter]) } end end end if params['pending'] if admin? data = App.all(:pending => true).map{|a| a.settings || {}} else data = [] end end if params['recent'] && params['recent'].length > 0 data = data.sort{|a, b| b['added'] <=> a['added'] } cutoff = (Time.now - (60 * 60 * 24 * 7 * 24)).utc.iso8601 recent = data.select{|e| e['added'] > cutoff} if recent.length < 6 data = data[0, 6] else data = recent end end if params['public'] && params['public'].length > 0 data = data.select{|e| (e['app_type'] == 'open_launch' || e['app_type'] == 'data') } end if params['platform'] && params['platform'].length > 0 data = data.select{|e| (!e['doesnt_work'] || !e['doesnt_work'].include?(params['platform'])) && (!e['only_works'] || e['only_works'].include?(params['platform'])) } # if params['platform'] == 'Canvas' # bad_tools = ['titanpad', 'flickr'] # data = data.select{|e| !bad_tools.include?(e['id']) } # else # bad_tools = ['wolfram', 'wiktionary', 'graph_builder'] # data = data.select{|e| !bad_tools.include?(e['id']) } # end end found_data = data if paginated found_data = found_data[offset, limit] end summaries = App.all(:tool_id => found_data.map{|d| d['id'] }) found_data = found_data.map do |tool| summary = summaries.detect{|s| s.tool_id == tool['id'] } fix_tool(tool, summary || false) end if paginated next_url = data.length > offset + limit ? (host + "/api/v1/apps?offset=#{offset + limit}") : nil if next_url ['filter', 'no_meta', 'category', 'level', 'extension', 'recent', 'public', 'platform', 'pending'].each do |key| next_url += "&#{key}=#{CGI.escape(params[key])}" if params[key] end response.headers['Link'] = "<#{next_url}>; rel=\"next\"" end if params['no_meta'] found_data else { :meta => {:next => next_url}, :current_offset => offset, :limit => limit, :objects => found_data } end else data end end def fix_tool(tool, tool_summary) host = request.scheme + "://" + request.host_with_port if tool_summary tool['ratings_count'] = tool_summary.ratings_count tool['comments_count'] = tool_summary.comments_count tool['avg_rating'] = tool_summary.avg_rating end tool['ratings_count'] ||= 0 tool['comments_count'] ||= 0 tool['banner_url'] ||= "/tools/#{tool['id']}/banner.png" tool['logo_url'] ||= "/tools/#{tool['id']}/logo.png" tool['icon_url'] ||= "/tools/#{tool['id']}/icon.png" cutoff = (Time.now - (60 * 60 * 24 * 7 * 24)).utc.iso8601 tool['new'] = tool['added'] && tool['added'] > cutoff tool['config_url'] ||= "/tools/#{tool['id']}/config.xml" if !tool['config_directions'] if tool['app_type'] == 'data' tool['data_url'] ||= "/tools/#{tool['id']}/data.json" tool['extensions'] = ["editor_button", "resource_selection"] tool['any_key'] = true tool['preview'] ||= { "url" => "/tools/public_collections/index.html?tool=#{tool['id']}", "height" => tool['height'] || 475 } elsif tool['app_type'] == 'open_launch' tool['any_key'] = true tool['extensions'] = ["editor_button", "resource_selection"] tool['preview'] ||= { "url" => "/tools/#{tool['id']}/index.html", "height" => tool['height'] || 475 } end ['big_image_url', 'image_url', 'icon_url', 'banner_url', 'logo_url', 'config_url', 'launch_url'].each do |key| tool[key] = prepend_host(tool[key], host) if tool[key] end tool end def prepend_host(path, host) if path.is_a?(Array) return path.map do |elem| elem['url'] = prepend_host(elem['url'], host) elem end end path = host + path if path && path.match(/^\//) path end def json_result(json) if params['callback'] return "#{params['callback']}(#{json})" else return json end end def review_as_json(review) fields = [:id, :user_name, :user_url, :user_avatar_url, :tool_name, :rating, :comments, :source_name, :source_url] res = {} res['created'] = review.created_at.strftime("%b %e, %Y") fields.each do |field| res[field] = review.send(field) end res end def confirm_token if session[:user_key] @token = ExternalAccessToken.first(:name => "LTI-Examples", :active => true) @internal_token = true else @token = ExternalAccessToken.first(:token => params['access_token'], :active => true) end if !@token @error = {:message => "Invalid token", :type => "error"}.to_json false else @token end end def get_tool id = params[:tool_id] @tool_summary = App.first(:tool_id => id ) if @tool_summary && @tool_summary.pending @tool_summary = nil unless admin?(id) end if @tool_summary && @tool_summary.settings @tool = @tool_summary.settings else data = App.load_apps @tool = data.detect{|t| t['id'] == id } @tool_summary = App.first_or_create(:tool_id => @tool['id'] ) if @tool && !@tool['pending'] end if !@tool @error = {:message => "Tool not found", :type => "error"}.to_json false else @tool end end end end register Apps end
require 'xmlrpc/client' require 'params_check' require 'mimemagic' require 'nokogiri' module Wordpress class Blog include ParamsCheck include Loggable def initialize(params = {}) @blog_uri = URI.parse(check_param(params, :blog_uri)) @xmlrpc_path = params[:xmlrpc_path] || "xmlrpc" @id = params[:blog_id] || 0 @user = check_param(params, :user) @password = check_param(params, :password) @client = XMLRPC::Client.new2(URI.join(@blog_uri.to_s, @xmlrpc_path).to_s) end #initialize def get_post(post_id) Post.new(api_call("metaWeblog.getPost", post_id, @user, @password)) end #get_post def recent_posts(number_of_posts) blog_api_call("metaWeblog.getRecentPosts", number_of_posts).collect do |struct| Post.from_struct(struct) end end #recent_posts def publish(post) process_post_images(post) post.id = blog_api_call("metaWeblog.newPost", post.to_struct, true).to_i post.published = true end #publish def update_post(post) process_post_images(post) return api_call("metaWeblog.editPost", post.id, @user, @password, post.to_struct, post.published) end #update_post def upload_file(file) struct = { :name => File.basename(file.path), :type => MimeMagic.by_magic(file).type, :bits => XMLRPC::Base64.new(File.open(file.path, "r").read), :overwrite => true } return blog_api_call("wp.uploadFile", struct) end private def process_post_images(post) doc = Nokogiri::HTML::DocumentFragment.parse(post.content) post.images.each do |image| raise ArgumentError, "Image not found (path: #{image[:file_path]})" unless File.exist?(image[:file_path]) basename = File.basename(image[:file_path]) uploaded_image = upload_file(File.open(image[:file_path], "rb")) raise "Image upload failed" if uploaded_image.nil? doc.css("img").each do |img| img['src'] = uploaded_image['url'] if img['src'].include?(basename) end end post.content = doc.to_html end #process_post_images def api_call(method_name, *args) begin return @client.call(method_name, *args) rescue XMLRPC::FaultException log.log_exception "Error while calling #{method_name}", $! raise APICallException, "Error while calling #{method_name}" end end #api_call def blog_api_call(method_name, *args) begin return @client.call(method_name, @id, @user, @password, *args) rescue XMLRPC::FaultException log.log_exception "Error while calling #{method_name}", $! raise APICallException, "Error while calling #{method_name}" end end #call_client end end changed xmlrpc reference to xmlrpc.php require 'xmlrpc/client' require 'params_check' require 'mimemagic' require 'nokogiri' module Wordpress class Blog include ParamsCheck include Loggable def initialize(params = {}) @blog_uri = URI.parse(check_param(params, :blog_uri)) @xmlrpc_path = params[:xmlrpc_path] || "xmlrpc.php" @id = params[:blog_id] || 0 @user = check_param(params, :user) @password = check_param(params, :password) @client = XMLRPC::Client.new2(URI.join(@blog_uri.to_s, @xmlrpc_path).to_s) end #initialize def get_post(post_id) Post.new(api_call("metaWeblog.getPost", post_id, @user, @password)) end #get_post def recent_posts(number_of_posts) blog_api_call("metaWeblog.getRecentPosts", number_of_posts).collect do |struct| Post.from_struct(struct) end end #recent_posts def publish(post) process_post_images(post) post.id = blog_api_call("metaWeblog.newPost", post.to_struct, true).to_i post.published = true end #publish def update_post(post) process_post_images(post) return api_call("metaWeblog.editPost", post.id, @user, @password, post.to_struct, post.published) end #update_post def upload_file(file) struct = { :name => File.basename(file.path), :type => MimeMagic.by_magic(file).type, :bits => XMLRPC::Base64.new(File.open(file.path, "r").read), :overwrite => true } return blog_api_call("wp.uploadFile", struct) end private def process_post_images(post) doc = Nokogiri::HTML::DocumentFragment.parse(post.content) post.images.each do |image| raise ArgumentError, "Image not found (path: #{image[:file_path]})" unless File.exist?(image[:file_path]) basename = File.basename(image[:file_path]) uploaded_image = upload_file(File.open(image[:file_path], "rb")) raise "Image upload failed" if uploaded_image.nil? doc.css("img").each do |img| img['src'] = uploaded_image['url'] if img['src'].include?(basename) end end post.content = doc.to_html end #process_post_images def api_call(method_name, *args) begin return @client.call(method_name, *args) rescue XMLRPC::FaultException log.log_exception "Error while calling #{method_name}", $! raise APICallException, "Error while calling #{method_name}" end end #api_call def blog_api_call(method_name, *args) begin return @client.call(method_name, @id, @user, @password, *args) rescue XMLRPC::FaultException log.log_exception "Error while calling #{method_name}", $! raise APICallException, "Error while calling #{method_name}" end end #call_client end end
# encoding: utf-8 require_relative 'tracker-client' require_relative 'slack-client' require_relative 'cve-tags' class StackCVENotifier < Struct.new(:cve_history, :cves_dir, :stacks_dir) def run!(system_name, system_shorthand, notifiers_to_execute_only_with_cves, notifiers_to_always_execute) cve_tags = CVETags.new(stacks_dir) related_cves = cve_tags.related_cves(system_name) unrelated_cves = cve_tags.unrelated_cves(system_name) { related_cves => "#{system_shorthand}.yaml", unrelated_cves => "#{system_shorthand}-unrelated.yaml" }.each do |cves, filename| next if cves.empty? rss_cve_titles = cves.map { |cve| cve[:title] } old_cve_titles = cve_history.read_yaml_cves(filename) new_cve_titles = rss_cve_titles - old_cve_titles new_cves = cves.select { |cve| new_cve_titles.include? cve[:title] } notifiers_to_always_execute.each { |n| n.notify! new_cves, !filename.include?('unrelated') } next if new_cves.empty? notifiers_to_execute_only_with_cves.each { |n| n.notify! new_cves, !filename.include?('unrelated') } new_cve_titles = new_cves.map { |cve| cve[:title] } cve_history.write_yaml_cves(new_cve_titles | old_cve_titles, File.join(cves_dir, filename) ) end ci_skip_message = (related_cves.empty? ? ' [ci skip]' : '') Dir.chdir(cves_dir) do raise 'command failed' unless system('git add -A') raise 'command failed' unless system("git commit -m 'CVE update#{ci_skip_message}'") end end end Have StackCVENotifier make separate commits for unrelated CVEs and stacks-related CVEs [#112900039] Signed-off-by: David Jahn <ea2208fe99a56ed20c9ae20b0a1446b61f13a269@gmail.com> # encoding: utf-8 require_relative 'tracker-client' require_relative 'slack-client' require_relative 'cve-tags' class StackCVENotifier < Struct.new(:cve_history, :cves_dir, :stacks_dir) def run!(system_name, system_shorthand, notifiers_to_execute_only_with_cves, notifiers_to_always_execute) cve_tags = CVETags.new(stacks_dir) related_cves = cve_tags.related_cves(system_name) unrelated_cves = cve_tags.unrelated_cves(system_name) { related_cves => "#{system_shorthand}.yaml", unrelated_cves => "#{system_shorthand}-unrelated.yaml" }.each do |cves, filename| next if cves.empty? rss_cve_titles = cves.map { |cve| cve[:title] } old_cve_titles = cve_history.read_yaml_cves(filename) new_cve_titles = rss_cve_titles - old_cve_titles new_cves = cves.select { |cve| new_cve_titles.include? cve[:title] } notifiers_to_always_execute.each { |n| n.notify! new_cves, !filename.include?('unrelated') } next if new_cves.empty? notifiers_to_execute_only_with_cves.each { |n| n.notify! new_cves, !filename.include?('unrelated') } new_cve_titles = new_cves.map { |cve| cve[:title] } cve_history.write_yaml_cves(new_cve_titles | old_cve_titles, File.join(cves_dir, filename) ) ci_skip_message = ((filename.include? 'unrelated') ? ' [ci skip]' : '') Dir.chdir(cves_dir) do raise 'command failed' unless system('git add -A') raise 'command failed' unless system("git commit -m 'CVE update#{ci_skip_message}'") end end end end
module Stagehand module Database extend self @@connection_name_stack = [Rails.env.to_sym] def connected_to_production? current_connection_name == Configuration.production_connection_name end def connected_to_staging? current_connection_name == Configuration.staging_connection_name end def staging_connection StagingProbe.connection end def production_connection ProductionProbe.connection end def with_connection(connection_name) different = !Configuration.ghost_mode? && current_connection_name != connection_name.to_sym @@connection_name_stack.push(connection_name.to_sym) Rails.logger.debug "Connecting to #{current_connection_name}" connect_to(current_connection_name) if different yield ensure @@connection_name_stack.pop Rails.logger.debug "Restoring connection to #{current_connection_name}" connect_to(current_connection_name) if different end def set_connection_for_model(model, connection_name) connect_to(connection_name, model) unless Configuration.ghost_mode? end private def connect_to(connection_name, model = ActiveRecord::Base) model.establish_connection(connection_name) end def current_connection_name @@connection_name_stack.last end # CLASSES class StagingProbe < ActiveRecord::Base self.abstract_class = true def self.init_connection establish_connection(Configuration.staging_connection_name) end init_connection end class ProductionProbe < ActiveRecord::Base self.abstract_class = true def self.init_connection establish_connection(Configuration.production_connection_name) end init_connection end end end Added methods to return the staging and production database name module Stagehand module Database extend self @@connection_name_stack = [Rails.env.to_sym] def connected_to_production? current_connection_name == Configuration.production_connection_name end def connected_to_staging? current_connection_name == Configuration.staging_connection_name end def production_connection ProductionProbe.connection end def staging_connection StagingProbe.connection end def production_database_name database_name(Configuration.production_connection_name) end def staging_database_name database_name(Configuration.staging_connection_name) end def with_connection(connection_name) different = !Configuration.ghost_mode? && current_connection_name != connection_name.to_sym @@connection_name_stack.push(connection_name.to_sym) Rails.logger.debug "Connecting to #{current_connection_name}" connect_to(current_connection_name) if different yield ensure @@connection_name_stack.pop Rails.logger.debug "Restoring connection to #{current_connection_name}" connect_to(current_connection_name) if different end def set_connection_for_model(model, connection_name) connect_to(connection_name, model) unless Configuration.ghost_mode? end private def connect_to(connection_name, model = ActiveRecord::Base) model.establish_connection(connection_name) end def current_connection_name @@connection_name_stack.last end def database_name(connection_name) Rails.configuration.database_configuration[connection_name.to_s]['database'] end # CLASSES class StagingProbe < ActiveRecord::Base self.abstract_class = true def self.init_connection establish_connection(Configuration.staging_connection_name) end init_connection end class ProductionProbe < ActiveRecord::Base self.abstract_class = true def self.init_connection establish_connection(Configuration.production_connection_name) end init_connection end end end
module StarScope::Lang module Go FUNC_CALL = /([\w\.]*?\w)\(/ END_OF_BLOCK = /^\s*\}\s*$/ END_OF_GROUP = /^\s*\)\s*$/ BUILTIN_FUNCS = ['new', 'make', 'len', 'close', 'copy', 'delete', 'int', 'int8', 'int16', 'int32', 'int64', 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'string', 'byte'] CONTROL_KEYS = ['if', 'for', 'switch', 'case'] def self.match_file(name) name.end_with?(".go") end def self.extract(file, &block) stack = [] scope = [] str = File.readlines(file).each_with_index do |line, line_no| line_no += 1 # zero-index to one-index # strip single-line comments like // foo match = /(.*)\/\//.match(line) line = match[1] if match # strip single-line comments like foo /* foo */ foo match = /(.*?)\/\*.*\*\/(.*)/.match(line) line = match[1] + match[2] if match # strip end-of-line comment starters like foo /* foo \n match = /(.*?)\/\*/.match(line) line = match[1] if match ends_with_comment = !match.nil? # if we're in a block comment, wait for it to end if stack[-1] == :comment match = /\*\/(.*)/.match(line) next unless match line = match[1] stack.pop end # poor-man's parser case stack[-1] when :struct case line when END_OF_BLOCK end_block(line_no, scope, stack, &block) when /(.+)\s+\w+/ parse_def($1, line_no, scope, &block) end when :interface case line when END_OF_BLOCK end_block(line_no, scope, stack, &block) when /(\w+)\(.*\)\s+/ yield :defs, scope + [$1], :line_no => line_no end when :def case line when END_OF_GROUP stack.pop when /(.+)\s*=.*/ parse_def($1, line_no, scope, &block) parse_call(line, line_no, scope, &block) else parse_def(line, line_no, scope, &block) end when :import case line when END_OF_GROUP stack.pop when /"(.+)"/ name = $1.split('/') yield :imports, name, :line_no => line_no end when :func case line when /^\}/ yield :end, "}", :line_no => line_no, :type => :func stack.pop else parse_new_line(line, line_no, scope, stack, &block) end else parse_new_line(line, line_no, scope, stack, &block) end # if the line looks like "foo /* foo" then we enter the comment state # after parsing the usable part of the line if ends_with_comment stack.push(:comment) end end end # handles new lines (when not in the middle of an existing definition) def self.parse_new_line(line, line_no, scope, stack, &block) case line when /^func\s+(\w+)\(/ yield :defs, scope + [$1], :line_no => line_no, :type => :func stack.push(:func) when /^func\s+\(\w+\s+\*?(\w+)\)\s*(\w+)\(/ yield :defs, scope + [$1, $2], :line_no => line_no, :type => :func stack.push(:func) when /^package\s+(\w+)/ scope.push($1) yield :defs, scope, :line_no => line_no, :type => :package when /^type\s+(\w+)\s+struct\s*\{/ scope.push($1) stack.push(:struct) yield :defs, scope, :line_no => line_no, :type => :class when /^type\s+(\w+)\s+interface\s*\{/ scope.push($1) stack.push(:interface) yield :defs, scope, :line_no => line_no, :type => :class when /^type\s+(\w+)/ yield :defs, scope + [$1], :line_no => line_no, :type => :type when /^import\s+"(.+)"/ name = $1.split('/') yield :imports, name, :line_no => line_no when /^import\s+\(/ stack.push(:import) when /^var\s+\(/ stack.push(:def) when /^var\s+(\w+)\s/ yield :defs, scope + [$1], :line_no => line_no parse_call(line, line_no, scope, &block) when /^const\s+\(/ stack.push(:def) when /^const\s+(\w+)\s/ yield :defs, scope + [$1], :line_no => line_no parse_call(line, line_no, scope, &block) when /^\s+(.*?) :?=[^=]/ $1.split(' ').each do |var| next if CONTROL_KEYS.include?(var) name = var.delete(',').split('.') next if name[0] == "_" # assigning to _ is a discard in golang if name.length == 1 yield :assigns, scope + [name[0]], :line_no => line_no else yield :assigns, name, :line_no => line_no end end parse_call(line, line_no, scope, &block) else parse_call(line, line_no, scope, &block) end end def self.parse_call(line, line_no, scope) line.scan(FUNC_CALL) do |match| name = match[0].split('.').select {|chunk| not chunk.empty?} if name.length == 1 next if name[0] == 'func' if BUILTIN_FUNCS.include?(name[0]) yield :calls, name[0], :line_no => line_no else yield :calls, scope + [name[0]], :line_no => line_no end else yield :calls, name, :line_no => line_no end end end def self.parse_def(line, line_no, scope) # if it doesn't start with a valid identifier character, it's probably # part of a multi-line literal and we should skip it return if not line =~ /^\s*[[:alpha:]_]/ line.split.each do |var| yield :defs, scope + [var.delete(',')], :line_no => line_no break if not var.end_with?(',') end end def self.end_block(line_no, scope, stack) yield :end, scope + ["}"], :line_no => line_no, :type => :class stack.pop scope.pop end end end Remove unused variable module StarScope::Lang module Go FUNC_CALL = /([\w\.]*?\w)\(/ END_OF_BLOCK = /^\s*\}\s*$/ END_OF_GROUP = /^\s*\)\s*$/ BUILTIN_FUNCS = ['new', 'make', 'len', 'close', 'copy', 'delete', 'int', 'int8', 'int16', 'int32', 'int64', 'uint', 'uint8', 'uint16', 'uint32', 'uint64', 'string', 'byte'] CONTROL_KEYS = ['if', 'for', 'switch', 'case'] def self.match_file(name) name.end_with?(".go") end def self.extract(file, &block) stack = [] scope = [] File.readlines(file).each_with_index do |line, line_no| line_no += 1 # zero-index to one-index # strip single-line comments like // foo match = /(.*)\/\//.match(line) line = match[1] if match # strip single-line comments like foo /* foo */ foo match = /(.*?)\/\*.*\*\/(.*)/.match(line) line = match[1] + match[2] if match # strip end-of-line comment starters like foo /* foo \n match = /(.*?)\/\*/.match(line) line = match[1] if match ends_with_comment = !match.nil? # if we're in a block comment, wait for it to end if stack[-1] == :comment match = /\*\/(.*)/.match(line) next unless match line = match[1] stack.pop end # poor-man's parser case stack[-1] when :struct case line when END_OF_BLOCK end_block(line_no, scope, stack, &block) when /(.+)\s+\w+/ parse_def($1, line_no, scope, &block) end when :interface case line when END_OF_BLOCK end_block(line_no, scope, stack, &block) when /(\w+)\(.*\)\s+/ yield :defs, scope + [$1], :line_no => line_no end when :def case line when END_OF_GROUP stack.pop when /(.+)\s*=.*/ parse_def($1, line_no, scope, &block) parse_call(line, line_no, scope, &block) else parse_def(line, line_no, scope, &block) end when :import case line when END_OF_GROUP stack.pop when /"(.+)"/ name = $1.split('/') yield :imports, name, :line_no => line_no end when :func case line when /^\}/ yield :end, "}", :line_no => line_no, :type => :func stack.pop else parse_new_line(line, line_no, scope, stack, &block) end else parse_new_line(line, line_no, scope, stack, &block) end # if the line looks like "foo /* foo" then we enter the comment state # after parsing the usable part of the line if ends_with_comment stack.push(:comment) end end end # handles new lines (when not in the middle of an existing definition) def self.parse_new_line(line, line_no, scope, stack, &block) case line when /^func\s+(\w+)\(/ yield :defs, scope + [$1], :line_no => line_no, :type => :func stack.push(:func) when /^func\s+\(\w+\s+\*?(\w+)\)\s*(\w+)\(/ yield :defs, scope + [$1, $2], :line_no => line_no, :type => :func stack.push(:func) when /^package\s+(\w+)/ scope.push($1) yield :defs, scope, :line_no => line_no, :type => :package when /^type\s+(\w+)\s+struct\s*\{/ scope.push($1) stack.push(:struct) yield :defs, scope, :line_no => line_no, :type => :class when /^type\s+(\w+)\s+interface\s*\{/ scope.push($1) stack.push(:interface) yield :defs, scope, :line_no => line_no, :type => :class when /^type\s+(\w+)/ yield :defs, scope + [$1], :line_no => line_no, :type => :type when /^import\s+"(.+)"/ name = $1.split('/') yield :imports, name, :line_no => line_no when /^import\s+\(/ stack.push(:import) when /^var\s+\(/ stack.push(:def) when /^var\s+(\w+)\s/ yield :defs, scope + [$1], :line_no => line_no parse_call(line, line_no, scope, &block) when /^const\s+\(/ stack.push(:def) when /^const\s+(\w+)\s/ yield :defs, scope + [$1], :line_no => line_no parse_call(line, line_no, scope, &block) when /^\s+(.*?) :?=[^=]/ $1.split(' ').each do |var| next if CONTROL_KEYS.include?(var) name = var.delete(',').split('.') next if name[0] == "_" # assigning to _ is a discard in golang if name.length == 1 yield :assigns, scope + [name[0]], :line_no => line_no else yield :assigns, name, :line_no => line_no end end parse_call(line, line_no, scope, &block) else parse_call(line, line_no, scope, &block) end end def self.parse_call(line, line_no, scope) line.scan(FUNC_CALL) do |match| name = match[0].split('.').select {|chunk| not chunk.empty?} if name.length == 1 next if name[0] == 'func' if BUILTIN_FUNCS.include?(name[0]) yield :calls, name[0], :line_no => line_no else yield :calls, scope + [name[0]], :line_no => line_no end else yield :calls, name, :line_no => line_no end end end def self.parse_def(line, line_no, scope) # if it doesn't start with a valid identifier character, it's probably # part of a multi-line literal and we should skip it return if not line =~ /^\s*[[:alpha:]_]/ line.split.each do |var| yield :defs, scope + [var.delete(',')], :line_no => line_no break if not var.end_with?(',') end end def self.end_block(line_no, scope, stack) yield :end, scope + ["}"], :line_no => line_no, :type => :class stack.pop scope.pop end end end
module DataAnon module Strategy class Whitelist include Utils::Logging def initialize name @name = name @fields = {} end def process_fields &block block.call self self end def primary_key field @primary_key = field end def whitelist *fields fields.each { |f| @fields[f.downcase] = DataAnon::Strategy::Field::Whitelist.new } end def fields @fields end def anonymize *fields fields.each { |f| @fields[f.downcase] = DataAnon::Strategy::Field::DefaultAnon.new } temp = self return Class.new do @temp_fields = fields @table_fields = temp.fields def self.using field_strategy @temp_fields.each { |f| @table_fields[f.downcase] = field_strategy } end end end def process source = Utils::SourceTable.create @name, @primary_key dest = Utils::DestinationTable.create @name, @primary_key logger.debug "Processing table #{@name} with fields strategy using #{@fields}" progress_logger.info "Table: #{@name} " index = 1 source.all.each do |record| progress_logger.info "." dest_record_map = {} record.attributes.each do | field_name, field_value | field = DataAnon::Core::Field.new(field_name, field_value, index, record) dest_record_map[field_name] = @fields[field_name.downcase].anonymize(field) end dest_record = dest.new dest_record_map dest_record.save! index += 1 end progress_logger.info " DONE\n" end end end end Default anonymization strategy for all fields in table set to the default strategy module DataAnon module Strategy class Whitelist include Utils::Logging def initialize name @name = name @fields = {} end def process_fields &block block.call self self end def primary_key field @primary_key = field end def whitelist *fields fields.each { |f| @fields[f.downcase] = DataAnon::Strategy::Field::Whitelist.new } end def fields @fields end def anonymize *fields fields.each { |f| @fields[f.downcase] = DataAnon::Strategy::Field::DefaultAnon.new } temp = self return Class.new do @temp_fields = fields @table_fields = temp.fields def self.using field_strategy @temp_fields.each { |f| @table_fields[f.downcase] = field_strategy } end end end def process source = Utils::SourceTable.create @name, @primary_key dest = Utils::DestinationTable.create @name, @primary_key logger.debug "Processing table #{@name} with fields strategy using #{@fields}" progress_logger.info "Table: #{@name} " index = 1 source.all.each do |record| progress_logger.info "." dest_record_map = {} record.attributes.each do | field_name, field_value | field = DataAnon::Core::Field.new(field_name, field_value, index, record) field_strategy = @fields[field_name.downcase] || DataAnon::Strategy::Field::DefaultAnon.new dest_record_map[field_name] = field_strategy.anonymize(field) end dest_record = dest.new dest_record_map dest_record.save! index += 1 end progress_logger.info " DONE\n" end end end end
require "surveygizmo/client/version" require "oauth" module Surveygizmo class Client API_URL = "http://restapi.surveygizmo.com/v4" def initialize(omniauth_data) access_token_data = omniauth_data['access_token'] consumer_data = access_token_data['consumer'] @consumer = create_consumer(consumer_data) @access_token = create_access_token(@consumer, access_token_data['token'], access_token_data['secret']) end def accountuser(page = 1, page_size = 20 ) get_paginated_resource("accountuser", page, page_size) end def contactlist(page = 1, page_size = 50) get_paginated_resource("contactlist", page, page_size) end def contactlist_contact(page = 1, page_size = 50, list_id) get_paginated_resource("contactlist/#{list_id}", page, page_size) end def survey(page = 1, page_size = 50) get_paginated_resource("survey", page, page_size) end def surveycampaign(page = 1, page_size = 50, survey_id) get_paginated_resource("survey/#{survey_id}/surveycampaign", page, page_size) end def surveycampaign_contact(page = 1, page_size = 50, survey_id, campaign_id) get_paginated_resource("survey/#{survey_id}/surveycampaign/#{campaign_id}/contact", page, page_size) end def add_contact_to_list(list_id, contact_params) parsed_response(post_request("/contactlist/#{list_id}?_method=POST#{contact_params}")) end def add_contact_to_campaign(survey_id, campaign_id, contact_params) parsed_response(put_request("/survey/#{survey_id}/surveycampaign/#{campaign_id}/contact/?_method=PUT&#{contact_params}")) end def update_campaign_contact(survey_id, campaign_id, contact_id, contact_params) parsed_response(post_request("survey/#{survey_id}/surveycampaign/#{campaign_id}/contact/#{contact_id}?_method=POST&#{contact_params}")) end private def get_paginated_resource(resource, page = 1, page_size = 50) parsed_response(get_request("/#{resource}.json?page=#{page}&resultsperpage=#{page_size}")) end def parsed_response(response) JSON.parse(response.body) end def get_request(endpoint, headers = {}) @access_token.get(endpoint, headers) end def put_request(endpoint, headers = {}) @access_token.put(endpoint, headers) end def post_request(endpoint, headers = {}) @access_token.get(endpoint, headers) end def create_consumer(consumer_data) OAuth::Consumer.new(consumer_data['key'], consumer_data['secret'], { :site => API_URL}) end def create_access_token(consumer, access_token, access_token_secret) OAuth::AccessToken.new(consumer, access_token, access_token_secret) end end end Allow filters on API calls. require "surveygizmo/client/version" require "oauth" module Surveygizmo class Client API_URL = "http://restapi.surveygizmo.com/v4" def initialize(omniauth_data) access_token_data = omniauth_data['access_token'] consumer_data = access_token_data['consumer'] @consumer = create_consumer(consumer_data) @access_token = create_access_token( @consumer, access_token_data['token'], access_token_data['secret'] ) end def accountuser(filters = [], page = 1, page_size = 20) get_paginated_resource("accountuser", filters, page, page_size) end def contactlist(page = 1, page_size = 50, filters = []) get_paginated_resource("contactlist", page, page_size, filters) end def contactlist_contact(page = 1, page_size = 50, filters = [], list_id) get_paginated_resource("contactlist/#{list_id}", page, page_size) end def survey(filters = [], page = 1, page_size = 50) get_paginated_resource("survey", filters, page, page_size) end def surveycampaign(page = 1,filters = [], page_size = 50, survey_id) get_paginated_resource( "survey/#{survey_id}/surveycampaign", filters, page, page_size ) end def surveycampaign_contact( page = 1, filters = [], page_size = 50, survey_id, campaign_id ) get_paginated_resource( "survey/#{survey_id}/surveycampaign/#{campaign_id}/contact", page, page_size ) end def add_contact_to_list(list_id, contact_params) parsed_response( post_request( "/contactlist/#{list_id}?_method=POST#{contact_params}" ) ) end def add_contact_to_campaign(survey_id, campaign_id, contact_params) parsed_response( put_request( "/survey/#{survey_id}/surveycampaign/"\ "#{campaign_id}/contact/?_method=PUT&#{contact_params}" ) ) end def update_campaign_contact( survey_id, campaign_id, contact_id, contact_params ) parsed_response( post_request( "survey/#{survey_id}/surveycampaign/"\ "#{campaign_id}/contact/#{contact_id}?_method=POST"\ "&#{contact_params}" ) ) end private def get_paginated_resource(resource, filters = [], page = 1, page_size = 50) filter = compose_filter(filters) parsed_response(get_request( "/#{resource}.json?page=#{page}&resultsperpage=#{page_size}#{filter}" ) ) end def parsed_response(response) JSON.parse(response.body) end def get_request(endpoint, headers = {}) @access_token.get(endpoint, headers) end def put_request(endpoint, headers = {}) @access_token.put(endpoint, headers) end def post_request(endpoint, headers = {}) @access_token.get(endpoint, headers) end def compose_filter(filters) usable_filters = filters.select do |f| f.size == 3 end usable_filters.each_with_object("").with_index do |(f, memo), index| memo << "&filter[field][#{index}]=#{f['field']}"\ "&filter[operator][#{index}]=#{f['operator']}"\ "&filter[value][#{index}]=#{f['value']}" end end def create_consumer(consumer_data) OAuth::Consumer.new( consumer_data['key'], consumer_data['secret'], { :site => API_URL} ) end def create_access_token(consumer, access_token, access_token_secret) OAuth::AccessToken.new(consumer, access_token, access_token_secret) end end end
# encoding: utf-8 require 'swissmatch/name' module SwissMatch # Represents an area, commonly identified by zip-code and city-name. # A unique zip code is determined by any of these: # * the postal ordering number # * zip code + zip code add on # * zip code + name (city) class ZipCode # @return [Integer] # The postal ordering number, also known as ONRP attr_reader :ordering_number # onrp # Described under "PLZ light", as field "PLZ-Typ" # * 10 = Domizil- und Fachadressen # * 20 = Nur Domiziladressen # * 30 = Nur Fach-PLZ # * 40 = Firmen-PLZ # * 80 = Postinterne PLZ (Angabe Zustellpoststelle auf Bundzetteln oder auf Sackanschriften) # # @return [Integer] # The type of the zip code in a numeric code, one of the values 10, 20, 30, 40 or 80. attr_reader :type # Described under "PLZ light", as field "Postleitzahl" # # @return [Integer] # The 4 digit numeric zip code attr_reader :code # @return [Integer] # The 2 digit numeric code addition, to distinguish zip codes with the same 4 digit code. attr_reader :add_on # @return [Integer] # The 6 digit numeric zip code and add-on (first 4 digits are the code, last 2 # digits the add-on). attr_reader :full_code # @return [SwissMatch::Canton] # The canton this zip code belongs to attr_reader :canton # @return [SwissMatch::Name] # The official name of this zip code (max. 27 characters) attr_reader :name # @return [SwissMatch::Name] # The official name of this zip code (max. 18 characters) attr_reader :name_short # @note This method exists mostly for internal purposes # # @return [String] # All names, short and long, as strings, without sequence number nor language. attr_reader :all_names # @return [Symbol] # The main language in the area of this zip code. One of :de, :fr, :it or :rt. attr_reader :language # @return [SwissMatch::Canton] # The second most used language in the area of this zip code. One of :de, :fr, :it or :rt. attr_reader :language_alternative # @return [Boolean] # Whether this ZipCode instance is included in the MAT[CH]sort sortfile attr_reader :sortfile_member # @return [SwissMatch::ZipCode] # By which postal office delivery of letters is usually taken care of. attr_reader :delivery_by # @return [SwissMatch::Community] # The largest community which belongs to this zip code. attr_reader :largest_community # @return [SwissMatch::Communities] # The communities which belong to this zip code. attr_reader :communities # @return [Date, nil] # The date from which on this zip code starts to be in use # # @see #in_use? attr_reader :valid_from # @return [Date, nil] # The date until which on this zip code is in use # # @see #in_use? attr_reader :valid_until def initialize( ordering_number, type, code, add_on, name, names, name_short, names_short, region_names, region_names_short, canton, language, language_alternative, sortfile_member, delivery_by, largest_community, communities, valid_from, valid_until = nil ) @ordering_number = ordering_number @type = type @code = code @add_on = add_on @full_code = code*100 + add_on @language = language @language_alternative = language_alternative @name = name.is_a?(Name) ? name : Name.new(name, language) @name_short = name_short.is_a?(Name) ? name_short : Name.new(name_short, language) @names = (names || [@name]).sort_by(&:sequence_number) @names_short = (names_short || [@name_short]).sort_by(&:sequence_number) @all_names = @names.map(&:to_s) | @names_short.map(&:to_s) @region_names = region_names @region_names_short = region_names_short @canton = canton @sortfile_member = sortfile_member @delivery_by = delivery_by == :self ? self : delivery_by @largest_community = largest_community @communities = communities @valid_from = valid_from @valid_until = valid_until end # @return [String] # The zip code add-on as 2 digit string, with leading zeros if necessary def two_digit_add_on "%02d" % @add_on end # @return [Array<String>] # The name of this zip code in all languages and normalizations (only unique values) def transliterated_names ( @all_names.map { |name| SwissMatch.transliterate1(name) } | @all_names.map { |name| SwissMatch.transliterate2(name) } ).uniq end # Since a zip code can - for any given language - have no name, exactly one name, # or even multiple names, it is sometimes difficult to write good code to # automatically provide well localized addresses. This method helps with that, in that # it guarantees a single name, as well chosen as possible. # It returns the name for the given language, and with the lowest running number, if # no name can be found for the given language, the primary name (@see #name) is # returned. # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [SwissMatch::Name] # A single name for the zip code, chosen by a 'best fit' algorithm. def suggested_name(language=nil) (language && @names.find { |name| name.language == language }) || @name end # Since a zip code can - for any given language - have no name, exactly one name, # or even multiple names, it is sometimes difficult to write good code to # automatically provide well localized addresses. This method helps with that, in that # it guarantees a single name, as well chosen as possible. # It returns the name for the given language, and with the lowest running number, if # no name can be found for the given language, the primary name (@see #name) is # returned. # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [SwissMatch::Name] # A single short name for the zip code, chosen by a 'best fit' algorithm. def suggested_short_name(language=nil) (language && @short_name.find { |name| name.language == language }) || @short_name end # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official names (max. 27 chars) of this zip code. def names(language=nil) language ? @names.select { |name| name.language == language } : @names end # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official short names (max. 18 chars) of this zip code. def names_short(language=nil) language ? @names_short.select { |name| name.language == language } : @names_short end # A region name is a name that can be used along a zip code and city, but must not replace # the city. For more information, read the section about the PLZ_P2 file, "Bezeichnungstyp" # with value "3". # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official region names (max. 27 chars) of this zip code. def region_names(language=nil) language ? @region_names.select { |name| name.language == language } : @region_names end # A region name is a name that can be used along a zip code and city, but must not replace # the city. For more information, read the section about the PLZ_P2 file, "Bezeichnungstyp" # with value "3". # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official short region names (max. 18 chars) of this zip code. def region_names_short(language=nil) language ? @region_names_short.select { |name| name.language == language } : @region_names_short end # Compare two zip codes by their ordering number (ONRP) # # @return [Integer] # Returns -1, 0 or 1. def <=>(other) @ordering_number <=> other.ordering_number end # @param [Date] at # The date for which to check the # # @return [Boolean] # Whether the zip code is in active use at the given date. def in_use?(at=Date.today) if @valid_from then if @valid_until then at.between?(@valid_from, @valid_until) else at >= @valid_from end elsif @valid_until at <= @valid_until else true end end # @param [Boolean] retain_references # If set to false, :delivery_by will be set to the ordering number, # :largest_community to the community_number, :communities to their respective # community numbers and :canton to the canton's license_tag. # # @return [Hash] # All properties of the zip code as a hash. def to_hash(retain_references=false) delivery_by = retain_references ? @delivery_by : (@delivery_by && @delivery_by.ordering_number) largest_community = retain_references ? @largest_community : (@largest_community && @largest_community.community_number) communities = retain_references ? @communities : @communities.map(&:community_number) canton = retain_references ? @canton : (@canton && @canton.license_tag) { :ordering_number => @ordering_number, :type => @type, :code => @code, :add_on => @add_on, :name => @name, :name_short => @name_short, :canton => canton, :language => @language, :language_alternative => @language_alternative, :sortfile_member => @sortfile_member, :delivery_by => delivery_by, :largest_community => largest_community, :communities => communities, :valid_from => @valid_from, :valid_until => @valid_until, } end # @private # @see Object#hash def hash [self.class, @ordering_number].hash end # @private # @see Object#eql? def eql?(other) self.class.eql?(other.class) && @ordering_number.eql?(other.ordering_number) end # @return [String] # The 4 digit code, followed by the name def to_s "#{@code} #{@name}" end # @return [String] # @see Object#inspect def inspect sprintf "\#<%s:%014x %s>", self.class, object_id, self end end end Added SwissMatch::ZipCode#reverse_name_transliteration_map. # encoding: utf-8 require 'swissmatch/name' module SwissMatch # Represents an area, commonly identified by zip-code and city-name. # A unique zip code is determined by any of these: # * the postal ordering number # * zip code + zip code add on # * zip code + name (city) class ZipCode # @return [Integer] # The postal ordering number, also known as ONRP attr_reader :ordering_number # onrp # Described under "PLZ light", as field "PLZ-Typ" # * 10 = Domizil- und Fachadressen # * 20 = Nur Domiziladressen # * 30 = Nur Fach-PLZ # * 40 = Firmen-PLZ # * 80 = Postinterne PLZ (Angabe Zustellpoststelle auf Bundzetteln oder auf Sackanschriften) # # @return [Integer] # The type of the zip code in a numeric code, one of the values 10, 20, 30, 40 or 80. attr_reader :type # Described under "PLZ light", as field "Postleitzahl" # # @return [Integer] # The 4 digit numeric zip code attr_reader :code # @return [Integer] # The 2 digit numeric code addition, to distinguish zip codes with the same 4 digit code. attr_reader :add_on # @return [Integer] # The 6 digit numeric zip code and add-on (first 4 digits are the code, last 2 # digits the add-on). attr_reader :full_code # @return [SwissMatch::Canton] # The canton this zip code belongs to attr_reader :canton # @return [SwissMatch::Name] # The official name of this zip code (max. 27 characters) attr_reader :name # @return [SwissMatch::Name] # The official name of this zip code (max. 18 characters) attr_reader :name_short # @note This method exists mostly for internal purposes # # @return [String] # All names, short and long, as strings, without sequence number nor language. attr_reader :all_names # @return [Symbol] # The main language in the area of this zip code. One of :de, :fr, :it or :rt. attr_reader :language # @return [SwissMatch::Canton] # The second most used language in the area of this zip code. One of :de, :fr, :it or :rt. attr_reader :language_alternative # @return [Boolean] # Whether this ZipCode instance is included in the MAT[CH]sort sortfile attr_reader :sortfile_member # @return [SwissMatch::ZipCode] # By which postal office delivery of letters is usually taken care of. attr_reader :delivery_by # @return [SwissMatch::Community] # The largest community which belongs to this zip code. attr_reader :largest_community # @return [SwissMatch::Communities] # The communities which belong to this zip code. attr_reader :communities # @return [Date, nil] # The date from which on this zip code starts to be in use # # @see #in_use? attr_reader :valid_from # @return [Date, nil] # The date until which on this zip code is in use # # @see #in_use? attr_reader :valid_until def initialize( ordering_number, type, code, add_on, name, names, name_short, names_short, region_names, region_names_short, canton, language, language_alternative, sortfile_member, delivery_by, largest_community, communities, valid_from, valid_until = nil ) @ordering_number = ordering_number @type = type @code = code @add_on = add_on @full_code = code*100 + add_on @language = language @language_alternative = language_alternative @name = name.is_a?(Name) ? name : Name.new(name, language) @name_short = name_short.is_a?(Name) ? name_short : Name.new(name_short, language) @names = (names || [@name]).sort_by(&:sequence_number) @names_short = (names_short || [@name_short]).sort_by(&:sequence_number) @all_names = @names.map(&:to_s) | @names_short.map(&:to_s) @region_names = region_names @region_names_short = region_names_short @canton = canton @sortfile_member = sortfile_member @delivery_by = delivery_by == :self ? self : delivery_by @largest_community = largest_community @communities = communities @valid_from = valid_from @valid_until = valid_until end # @return [String] # The zip code add-on as 2 digit string, with leading zeros if necessary def two_digit_add_on "%02d" % @add_on end # @return [Array<String>] # The name of this zip code in all languages and normalizations (only unique values) def transliterated_names ( @all_names.map { |name| SwissMatch.transliterate1(name) } | @all_names.map { |name| SwissMatch.transliterate2(name) } ).uniq end # @return [Hash<String, String>] # A map to get the names which match a transliteration def reverse_name_transliteration_map result = {} @all_names.map { |name| trans_name1 = SwissMatch.transliterate1(name) trans_name2 = SwissMatch.transliterate2(name) result[trans_name1] ||= [] result[trans_name2] ||= [] result[trans_name1] << name result[trans_name2] << name } result.each_value(&:uniq!) result end # Since a zip code can - for any given language - have no name, exactly one name, # or even multiple names, it is sometimes difficult to write good code to # automatically provide well localized addresses. This method helps with that, in that # it guarantees a single name, as well chosen as possible. # It returns the name for the given language, and with the lowest running number, if # no name can be found for the given language, the primary name (@see #name) is # returned. # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [SwissMatch::Name] # A single name for the zip code, chosen by a 'best fit' algorithm. def suggested_name(language=nil) (language && @names.find { |name| name.language == language }) || @name end # Since a zip code can - for any given language - have no name, exactly one name, # or even multiple names, it is sometimes difficult to write good code to # automatically provide well localized addresses. This method helps with that, in that # it guarantees a single name, as well chosen as possible. # It returns the name for the given language, and with the lowest running number, if # no name can be found for the given language, the primary name (@see #name) is # returned. # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [SwissMatch::Name] # A single short name for the zip code, chosen by a 'best fit' algorithm. def suggested_short_name(language=nil) (language && @short_name.find { |name| name.language == language }) || @short_name end # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official names (max. 27 chars) of this zip code. def names(language=nil) language ? @names.select { |name| name.language == language } : @names end # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official short names (max. 18 chars) of this zip code. def names_short(language=nil) language ? @names_short.select { |name| name.language == language } : @names_short end # A region name is a name that can be used along a zip code and city, but must not replace # the city. For more information, read the section about the PLZ_P2 file, "Bezeichnungstyp" # with value "3". # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official region names (max. 27 chars) of this zip code. def region_names(language=nil) language ? @region_names.select { |name| name.language == language } : @region_names end # A region name is a name that can be used along a zip code and city, but must not replace # the city. For more information, read the section about the PLZ_P2 file, "Bezeichnungstyp" # with value "3". # # @param [Symbol, nil] language # One of nil, :de, :fr, :it or :rt # # @return [Array<SwissMatch::Name>] # All official short region names (max. 18 chars) of this zip code. def region_names_short(language=nil) language ? @region_names_short.select { |name| name.language == language } : @region_names_short end # Compare two zip codes by their ordering number (ONRP) # # @return [Integer] # Returns -1, 0 or 1. def <=>(other) @ordering_number <=> other.ordering_number end # @param [Date] at # The date for which to check the # # @return [Boolean] # Whether the zip code is in active use at the given date. def in_use?(at=Date.today) if @valid_from then if @valid_until then at.between?(@valid_from, @valid_until) else at >= @valid_from end elsif @valid_until at <= @valid_until else true end end # @param [Boolean] retain_references # If set to false, :delivery_by will be set to the ordering number, # :largest_community to the community_number, :communities to their respective # community numbers and :canton to the canton's license_tag. # # @return [Hash] # All properties of the zip code as a hash. def to_hash(retain_references=false) delivery_by = retain_references ? @delivery_by : (@delivery_by && @delivery_by.ordering_number) largest_community = retain_references ? @largest_community : (@largest_community && @largest_community.community_number) communities = retain_references ? @communities : @communities.map(&:community_number) canton = retain_references ? @canton : (@canton && @canton.license_tag) { :ordering_number => @ordering_number, :type => @type, :code => @code, :add_on => @add_on, :name => @name, :name_short => @name_short, :canton => canton, :language => @language, :language_alternative => @language_alternative, :sortfile_member => @sortfile_member, :delivery_by => delivery_by, :largest_community => largest_community, :communities => communities, :valid_from => @valid_from, :valid_until => @valid_until, } end # @private # @see Object#hash def hash [self.class, @ordering_number].hash end # @private # @see Object#eql? def eql?(other) self.class.eql?(other.class) && @ordering_number.eql?(other.ordering_number) end # @return [String] # The 4 digit code, followed by the name def to_s "#{@code} #{@name}" end # @return [String] # @see Object#inspect def inspect sprintf "\#<%s:%014x %s>", self.class, object_id, self end end end
require 'formula' class Blasr < Formula homepage 'https://github.com/PacificBiosciences/blasr' head 'https://github.com/PacificBiosciences/blasr.git' depends_on 'hdf5' => 'enable-cxx' fails_with :clang do build 500 cause <<-EOS.undent error: destructor type 'HDFWriteBuffer<int>' in object destruction expression does not match the type 'BufferedHDFArray<int>' of the object being destroyed EOS end def install system 'make' system 'make', 'install', 'PREFIX=' + prefix end test do system 'blasr' end end blasr 2.1 require 'formula' class Blasr < Formula homepage 'https://github.com/PacificBiosciences/blasr' url 'https://github.com/PacificBiosciences/blasr/archive/smrtanalysis-2.1.tar.gz' sha1 'ac6add1ba8a82cac2515da36c0ec53060c20ea0f' head 'https://github.com/PacificBiosciences/blasr.git' depends_on 'hdf5' => 'enable-cxx' fails_with :clang do build 500 cause <<-EOS.undent error: destructor type 'HDFWriteBuffer<int>' in object destruction expression does not match the type 'BufferedHDFArray<int>' of the object being destroyed EOS end def install system 'make' system 'make', 'install', 'PREFIX=' + prefix end test do system 'blasr' end end
Add rake task to delete attachments which have an invalid attachable namespace :attachment do desc 'List and delete attachments with invalid attachables' task delete_where_attachable_invalid: :environment do # adding 'attachable: nil' to this 'where' doesn't work here: # doing so only keeps those with a null attachable_id in the # database; but if the attachable_id is invalid but non-null, the # attachable will be nil: # # irb> Attachment.find(566845).attachable # => nil # irb> Attachment.find(566845).attachable_id # => 330497 # Attachment.where(deleted: false).find_each do |attachment| next unless attachment.attachable == nil puts attachment.attachment_data.file.asset_manager_path if attachment.attachment_data && attachment.attachment_data.file attachment.destroy end end end
# encoding: UTF-8 desc "Import the XML rules to sites and policies" task :import_xml => :environment do end add policy creation code to the xml_import task # encoding: UTF-8 desc "Import the XML rules to sites and policies" task :import_xml => :environment do Dir.foreach(path) do |xml_file| # loop for each xml file/rule next if xml_file == "." || xml_file == ".." filecontent = File.open(path + xml_file) ngxml = Nokogiri::XML(filecontent) filecontent.close site = ngxml.xpath("//sitename[1]/@name").to_s ngxml.xpath("//sitename/docname").each do |doc| # docs << TOSBackDoc.new({site: site, name: doc.at_xpath("./@name").to_s, url: doc.at_xpath("./url/@name").to_s, xpath: doc.at_xpath("./url/@xpath").to_s, reviewed: doc.at_xpath("./url/@reviewed").to_s}) p = Policy.where(url:doc.at_xpath("./url/@name").to_s, xpath: doc.at_xpath("./url/@name").to_s).first unless p Policy.create do |p| p.name = doc.at_xpath("./@name").to_s p.url = doc.at_xpath("./url/@name").to_s p.xpath = (doc.at_xpath("./url/@xpath").to_s == "") ? nil : doc.at_xpath("./url/@xpath").to_s p.needs_revision = (doc.at_xpath("./url/@reviewed").to_s == "") ? true : nil p.lang = doc.at_xpath("./url/@lang").to_s == "") ? nil : doc.at_xpath("./url/@lang").to_s end end # unless p #TODO site association here. end end end
# Copyright (c) 2010-2011, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. namespace :migrations do task :upload_photos_to_s3 do require File.join(File.dirname(__FILE__), '..', '..', 'config', 'environment') puts AppConfig.environment.s3.key connection = Aws::S3.new( AppConfig.environment.s3.key, AppConfig.environment.s3.secret) bucket = connection.bucket(AppConfig.environment.s3.bucket) dir_name = File.dirname(__FILE__) + "/../../public/uploads/images/" count = Dir.foreach(dir_name).count current = 0 Dir.foreach(dir_name){|file_name| puts file_name; if file_name != '.' && file_name != '..'; begin key = Aws::S3::Key.create(bucket, 'uploads/images/' + file_name); key.put(File.open(dir_name+ '/' + file_name).read, 'public-read'); key.public_link(); puts "Uploaded #{current} of #{count}" current += 1 rescue => e puts "error #{e} on #{current} (#{file_name}), retrying" retry end end } end CURRENT_QUEUES = %w(urgent high medium low default).freeze desc "Migrate sidekiq jobs, retries, scheduled and dead jobs from any legacy queue to "\ "the default queue (retries all dead jobs)" task :legacy_queues do # Push all retries, scheduled and dead jobs to their queues Sidekiq::RetrySet.new.retry_all Sidekiq::DeadSet.new.retry_all Sidekiq::ScheduledSet.new.reject {|job| CURRENT_QUEUES.include? job.queue }.each(&:add_to_queue) # Move all jobs from legacy queues to the default queue Sidekiq::Queue.all.each do |queue| next if CURRENT_QUEUES.include? queue.name puts "Migrating #{queue.size} jobs from #{queue.name} to default..." queue.each do |job| job.item["queue"] = "default" Sidekiq::Client.push(job.item) job.delete end # Delete the queue queue.clear end end end Set redis url for sidekiq cleanup migration task closes #7125 # Copyright (c) 2010-2011, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. namespace :migrations do task :upload_photos_to_s3 do require File.join(File.dirname(__FILE__), '..', '..', 'config', 'environment') puts AppConfig.environment.s3.key connection = Aws::S3.new( AppConfig.environment.s3.key, AppConfig.environment.s3.secret) bucket = connection.bucket(AppConfig.environment.s3.bucket) dir_name = File.dirname(__FILE__) + "/../../public/uploads/images/" count = Dir.foreach(dir_name).count current = 0 Dir.foreach(dir_name){|file_name| puts file_name; if file_name != '.' && file_name != '..'; begin key = Aws::S3::Key.create(bucket, 'uploads/images/' + file_name); key.put(File.open(dir_name+ '/' + file_name).read, 'public-read'); key.public_link(); puts "Uploaded #{current} of #{count}" current += 1 rescue => e puts "error #{e} on #{current} (#{file_name}), retrying" retry end end } end CURRENT_QUEUES = %w(urgent high medium low default).freeze desc "Migrate sidekiq jobs, retries, scheduled and dead jobs from any legacy queue to "\ "the default queue (retries all dead jobs)" task :legacy_queues do Sidekiq.redis = AppConfig.get_redis_options # Push all retries, scheduled and dead jobs to their queues Sidekiq::RetrySet.new.retry_all Sidekiq::DeadSet.new.retry_all Sidekiq::ScheduledSet.new.reject {|job| CURRENT_QUEUES.include? job.queue }.each(&:add_to_queue) # Move all jobs from legacy queues to the default queue Sidekiq::Queue.all.each do |queue| next if CURRENT_QUEUES.include? queue.name puts "Migrating #{queue.size} jobs from #{queue.name} to default..." queue.each do |job| job.item["queue"] = "default" Sidekiq::Client.push(job.item) job.delete end # Delete the queue queue.clear end end end
require 'ostruct' namespace :panopticon do desc "Register application metadata with panopticon" task :register => :environment do require 'gds_api/panopticon' logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO } logger.info "Registering with panopticon..." registerer = GdsApi::Panopticon::Registerer.new(owning_app: "businesssupportfinder") record = OpenStruct.new( slug: APP_SLUG, title: "Business finance and support finder", description: "Find business finance, support, grants and loans backed by the government.", need_id: "B1017", prefixes: [APP_SLUG], state: "live", indexable_content: "Business finance and support finder") registerer.register(record) end end Update registered routes to match new scheme. They should now be full paths, not just slugs. require 'ostruct' namespace :panopticon do desc "Register application metadata with panopticon" task :register => :environment do require 'gds_api/panopticon' logger = GdsApi::Base.logger = Logger.new(STDERR).tap { |l| l.level = Logger::INFO } logger.info "Registering with panopticon..." registerer = GdsApi::Panopticon::Registerer.new(owning_app: "businesssupportfinder") record = OpenStruct.new( slug: APP_SLUG, title: "Business finance and support finder", description: "Find business finance, support, grants and loans backed by the government.", need_id: "B1017", paths: [], prefixes: ["/#{APP_SLUG}"], state: "live", indexable_content: "Business finance and support finder") registerer.register(record) end end
require 'fileutils' namespace :taskmaster do desc "Preview the generated crontab" task :preview do output = Taskmaster.cron_output puts output end desc "Write the generated crontab to config/schedule.rb -- suitable for whenever to write it to the system" task :write do output = Taskmaster.aggregate_whenever FileUtils.mkdir_p 'config' FileUtils.touch 'config/schedule.rb' File.open('config/schedule.rb', File::WRONLY) do |file| file << output end puts "Your crontab has been written to config/schedule.rb. Please use the whenever script to write it to your system crontab." end end add a warning to the generated schedule.rb require 'fileutils' namespace :taskmaster do desc "Preview the generated crontab" task :preview do output = Taskmaster.cron_output puts output end desc "Write the generated crontab to config/schedule.rb -- suitable for whenever to write it to the system" task :write do output = Taskmaster.aggregate_whenever FileUtils.mkdir_p 'config' FileUtils.touch 'config/schedule.rb' File.open('config/schedule.rb', File::WRONLY) do |file| file << "# DO NOT EDIT THIS FILE -- it should only be modified with the taskmaster:write Rake task" file << output end puts "Your crontab has been written to config/schedule.rb. Please use the whenever script to write it to your system crontab." end end
class RemoveDuplicateLinks < ActiveRecord::Migration def self.up for account_id, id in execute("select account_id, min(id) as count from account_links group by account_id") do execute("delete from account_links where account_id = #{account_id} and id != #{id}") end end def self.down end end modified migration to remove account_link_requests which has no account_link class RemoveDuplicateLinks < ActiveRecord::Migration def self.up for account_id, id in execute("select account_id, min(id) as count from account_links group by account_id") do execute("delete from account_links where account_id = #{account_id} and id != #{id}") end invalid_account_link_requests = [] for id, remote_id in execute "select account_link_requests.id, account_links.id as remote_id from account_link_requests left outer join account_links on account_links.user_id = account_link_requests.sender_id and account_links.account_id = account_link_requests.sender_ex_account_id where account_links.id is null" invalid_account_link_requests << id.to_s end execute("delete from account_link_requests where id in (#{invalid_account_link_requests.join(',')})") unless invalid_account_link_requests.empty? end def self.down end end
class AddSourceToMessages < ActiveRecord::Migration def change add_column :messages, :source, :string add_column :messages, :taxon_id, :integer change_column :messages, :viewd, :viewed add_column :messages, :phone, :string add_column :messages, :vendor, :string end end fix migration class AddSourceToMessages < ActiveRecord::Migration def change add_column :messages, :source, :string add_column :messages, :taxon_id, :integer rename_column :messages, :viewd, :viewed add_column :messages, :phone, :string add_column :messages, :vendor, :string end end
# frozen_string_literal: true require "unicode/display_width" module Textbringer class Buffer attr_accessor :name, :file_name, :file_encoding, :file_format, :keymap attr_reader :point, :marks GAP_SIZE = 256 UNDO_LIMIT = 1000 UTF8_CHAR_LEN = Hash.new(1) [ [0xc0..0xdf, 2], [0xe0..0xef, 3], [0xf0..0xf4, 4] ].each do |range, len| range.each do |c| UTF8_CHAR_LEN[c.chr] = len end end @@auto_detect_encodings = [ Encoding::UTF_8, Encoding::EUC_JP, Encoding::Windows_31J ] def initialize(s = "", name: nil, file_name: nil, file_encoding: Encoding::UTF_8) @contents = s.encode(Encoding::UTF_8) @contents.force_encoding(Encoding::ASCII_8BIT) @name = name @file_name = file_name @file_encoding = file_encoding case @contents when /(?<!\r)\n/ @file_format = :unix when /\r(?!\n)/ @file_format = :mac @contents.gsub!(/\r/, "\n") when /\r\n/ @file_format = :dos @contents.gsub!(/\r/, "") else @file_format = :unix end @point = 0 @gap_start = 0 @gap_end = 0 @marks = [] @mark = nil @column = nil @yank_start = new_mark @undo_stack = [] @redo_stack = [] @undoing = false @version = 0 @modified = false @keymap = nil end def modified? @modified end def self.open(file_name, name: File.basename(file_name)) s = File.read(file_name) enc = @@auto_detect_encodings.find { |e| s.force_encoding(e) s.valid_encoding? } Buffer.new(s, name: name, file_name: file_name, file_encoding: enc) end def save if @file_name.nil? raise "file name is not set" end s = to_s case @file_format when :dos s.gsub!(/\n/, "\r\n") when :mac s.gsub!(/\n/, "\r") end File.write(@file_name, s, encoding: @file_encoding) @version += 1 @modified = false end def to_s (@contents[0...@gap_start] + @contents[@gap_end..-1]).force_encoding(Encoding::UTF_8) end def substring(s, e) if s > @gap_start || e <= @gap_start @contents[user_to_gap(s)...user_to_gap(e)] else len = @gap_start - s @contents[user_to_gap(s), len] + @contents[@gap_end, e - s - len] end.force_encoding(Encoding::UTF_8) end def byte_after(location = @point) if location < @gap_start @contents.byteslice(location) else @contents.byteslice(location + gap_size) end end def char_after(location = @point) substring(location, location + UTF8_CHAR_LEN[byte_after(location)]) end def bytesize @contents.bytesize - gap_size end alias size bytesize def point_min 0 end def point_max bytesize end def goto_char(pos) if pos < 0 || pos > size raise RangeError, "Out of buffer" end @column = nil @point = pos end def insert(s, merge_undo = false) pos = @point size = s.bytesize adjust_gap(size) @contents[@point, size] = s.b @marks.each do |m| if m.location > @point m.location += size end end @point = @gap_start += size unless @undoing if merge_undo && @undo_stack.last.is_a?(InsertAction) @undo_stack.last.merge(s) @redo_stack.clear else push_undo(InsertAction.new(self, pos, s)) end end @modified = true @column = nil end def newline indentation = save_point { |saved| beginning_of_line s = @point while /[ \t]/ =~ char_after forward_char end str = substring(s, @point) if end_of_buffer? || char_after == "\n" delete_region(s, @point) end str } insert("\n" + indentation) end def delete_char(n = 1) adjust_gap s = @point pos = get_pos(@point, n) if n > 0 str = substring(s, pos) @gap_end += pos - @point @marks.each do |m| if m.location > @point m.location -= pos - @point end end push_undo(DeleteAction.new(self, s, s, str)) @modified = true elsif n < 0 str = substring(pos, s) @marks.each do |m| if m.location > @point m.location += pos - @point end end @point = @gap_start = pos push_undo(DeleteAction.new(self, s, pos, str)) @modified = true end @column = nil end def backward_delete_char(n = 1) delete_char(-n) end def forward_char(n = 1) @point = get_pos(@point, n) @column = nil end def backward_char(n = 1) forward_char(-n) end def forward_word(n = 1) n.times do while !end_of_buffer? && /\p{Letter}|\p{Number}/ !~ char_after forward_char end while !end_of_buffer? && /\p{Letter}|\p{Number}/ =~ char_after forward_char end end end def backward_word(n = 1) n.times do break if beginning_of_buffer? backward_char while !beginning_of_buffer? && /\p{Letter}|\p{Number}/ !~ char_after backward_char end while !beginning_of_buffer? && /\p{Letter}|\p{Number}/ =~ char_after backward_char end if /\p{Letter}|\p{Number}/ !~ char_after forward_char end end end def next_line if @column column = @column else prev_point = @point beginning_of_line column = Unicode::DisplayWidth.of(substring(@point, prev_point), 2) end end_of_line forward_char s = @point while !end_of_buffer? && byte_after != "\n" && Unicode::DisplayWidth.of(substring(s, @point), 2) < column forward_char end @column = column end def previous_line if @column column = @column else prev_point = @point beginning_of_line column = Unicode::DisplayWidth.of(substring(@point, prev_point), 2) end beginning_of_line backward_char beginning_of_line s = @point while !end_of_buffer? && byte_after != "\n" && Unicode::DisplayWidth.of(substring(s, @point), 2) < column forward_char end @column = column end def beginning_of_buffer @point = 0 end def beginning_of_buffer? @point == 0 end def end_of_buffer @point = bytesize end def end_of_buffer? @point == bytesize end def beginning_of_line while !beginning_of_buffer? && byte_after(@point - 1) != "\n" backward_char end @point end def end_of_line while !end_of_buffer? && byte_after(@point) != "\n" forward_char end @point end def new_mark Mark.new(self, @point).tap { |m| @marks << m } end def point_to_mark(mark) @point = mark.location end def mark_to_point(mark) mark.location = @point end def point_at_mark?(mark) @point == mark.location end def point_before_mark?(mark) @point < mark.location end def point_after_mark?(mark) @point > mark.location end def swap_point_and_mark(mark) @point, mark.location = mark.location, @point end def save_point saved = new_mark column = @column begin yield(saved) ensure point_to_mark(saved) saved.delete @column = column end end def mark if @mark.nil? raise "The mark is not set" end @mark.location end def set_mark(pos = @point) @mark ||= new_mark @mark.location = pos end def copy_region(s = @point, e = mark, append = false) str = s <= e ? substring(s, e) : substring(e, s) if append && !KILL_RING.empty? KILL_RING.current.concat(str) else KILL_RING.push(str) end end def kill_region(s = @point, e = mark, append = false) copy_region(s, e, append) delete_region(s, e) end def delete_region(s = @point, e = mark) save_point do old_pos = @point if s > e s, e = e, s end str = substring(s, e) @point = s adjust_gap @gap_end += e - s @marks.each do |m| if m.location > @point m.location -= e - s end end push_undo(DeleteAction.new(self, old_pos, s, str)) @modified = true end end def kill_line(append = false) save_point do |saved| if end_of_buffer? raise RangeError, "End of buffer" end if char_after == ?\n forward_char else end_of_line end pos = @point point_to_mark(saved) kill_region(@point, pos, append) end end def kill_word(append = false) save_point do |saved| if end_of_buffer? raise RangeError, "End of buffer" end forward_word pos = @point point_to_mark(saved) kill_region(@point, pos, append) end end def insert_for_yank(s) mark_to_point(@yank_start) insert(s) end def yank insert_for_yank(KILL_RING.current) end def yank_pop delete_region(@yank_start.location, @point) insert_for_yank(KILL_RING.current(1)) end def undo if @undo_stack.empty? raise "No further undo information" end action = @undo_stack.pop @undoing = true begin was_modified = @modified action.undo if action.version == @version @modified = false action.version = nil elsif !was_modified action.version = @version end @redo_stack.push(action) ensure @undoing = false end end def redo if @redo_stack.empty? raise "No further redo information" end action = @redo_stack.pop @undoing = true begin was_modified = @modified action.redo if action.version == @version @modified = false action.version = nil elsif !was_modified action.version = @version end @undo_stack.push(action) ensure @undoing = false end end def re_search_forward(s) re = Regexp.new(s) b, e = utf8_re_search(@contents, re, user_to_gap(@point)) if b.nil? raise "Search failed" end if b < @gap_end && e > @gap_start b, e = utf8_re_search(@contents, re, @gap_end) if b.nil? raise "Search failed" end end if /[\x80-\xbf]/n =~ @contents[e] raise "Search failed" end goto_char(gap_to_user(e)) end def transpose_chars if end_of_buffer? || char_after == "\n" backward_char end if beginning_of_buffer? raise RangeError, "Beginning of buffer" end backward_char c = char_after delete_char forward_char insert(c) end private def adjust_gap(min_size = 0) if @gap_start < @point len = user_to_gap(@point) - @gap_end @contents[@gap_start, len] = @contents[@gap_end, len] @gap_start += len @gap_end += len elsif @gap_start > @point len = @gap_start - @point @contents[@gap_end - len, len] = @contents[@point, len] @gap_start -= len @gap_end -= len end if gap_size < min_size new_gap_size = GAP_SIZE + min_size extended_size = new_gap_size - gap_size @contents[@gap_end, 0] = "\0" * extended_size @gap_end += extended_size end end def gap_size @gap_end - @gap_start end def user_to_gap(pos) if pos <= @gap_start pos else gap_size + pos end end def gap_to_user(gpos) if gpos <= @gap_start gpos elsif gpos >= @gap_end gpos - gap_size else raise RangeError, "Position is in gap" end end def get_pos(pos, offset) if offset >= 0 i = offset while i > 0 raise RangeError, "Out of buffer" if end_of_buffer? b = byte_after(pos) pos += UTF8_CHAR_LEN[b] raise RangeError, "Out of buffer" if pos > bytesize i -= 1 end else i = -offset while i > 0 pos -= 1 raise RangeError, "Out of buffer" if pos < 0 while /[\x80-\xbf]/n =~ byte_after(pos) pos -= 1 raise RangeError, "Out of buffer" if pos < 0 end i -= 1 end end pos end def push_undo(action) return if @undoing if @undo_stack.size >= UNDO_LIMIT @undo_stack[0, @undo_stack.size + 1 - UNDO_LIMIT] = [] end if !modified? action.version = @version end @undo_stack.push(action) @redo_stack.clear end def utf8_re_search(s, re, pos) char_pos = s[0...pos].force_encoding(Encoding::UTF_8).size s.force_encoding(Encoding::UTF_8) begin if s.index(re, char_pos) m = Regexp.last_match b = m.pre_match.bytesize e = b + m.to_s.bytesize [b, e] else nil end ensure s.force_encoding(Encoding::ASCII_8BIT) end end end class Mark attr_accessor :location def initialize(buffer, location) @buffer = buffer @location = location end def delete @buffer.marks.delete(self) end end class KillRing def initialize(max = 30) @max = max @ring = [] @current = -1 end def push(str) @current += 1 if @ring.size < @max @ring.insert(@current, str) else if @current == @max @current = 0 end @ring[@current] = str end end def current(n = 0) if @ring.empty? raise "Kill ring is empty" end @current -= n if @current < 0 @current += @ring.size end @ring[@current] end def empty? @ring.empty? end end KILL_RING = KillRing.new class UndoableAction attr_accessor :version def initialize(buffer, location) @version = nil @buffer = buffer @location = location end end class InsertAction < UndoableAction def initialize(buffer, location, string) super(buffer, location) @string = string end def undo @buffer.goto_char(@location) @buffer.delete_char(@string.size) end def redo @buffer.goto_char(@location) @buffer.insert(@string) end def merge(s) @string.concat(s) end end class DeleteAction < UndoableAction def initialize(buffer, location, insert_location, string) super(buffer, location) @insert_location = insert_location @string = string end def undo @buffer.goto_char(@insert_location) @buffer.insert(@string) @buffer.goto_char(@location) end def redo @buffer.goto_char(@insert_location) @buffer.delete_char(@string.size) end end end Ignore invalid byte sequence errors. # frozen_string_literal: true require "unicode/display_width" module Textbringer class Buffer attr_accessor :name, :file_name, :file_encoding, :file_format, :keymap attr_reader :point, :marks GAP_SIZE = 256 UNDO_LIMIT = 1000 UTF8_CHAR_LEN = Hash.new(1) [ [0xc0..0xdf, 2], [0xe0..0xef, 3], [0xf0..0xf4, 4] ].each do |range, len| range.each do |c| UTF8_CHAR_LEN[c.chr] = len end end @@auto_detect_encodings = [ Encoding::UTF_8, Encoding::EUC_JP, Encoding::Windows_31J ] def initialize(s = "", name: nil, file_name: nil, file_encoding: Encoding::UTF_8) @contents = s.encode(Encoding::UTF_8) @contents.force_encoding(Encoding::ASCII_8BIT) @name = name @file_name = file_name @file_encoding = file_encoding case @contents when /(?<!\r)\n/ @file_format = :unix when /\r(?!\n)/ @file_format = :mac @contents.gsub!(/\r/, "\n") when /\r\n/ @file_format = :dos @contents.gsub!(/\r/, "") else @file_format = :unix end @point = 0 @gap_start = 0 @gap_end = 0 @marks = [] @mark = nil @column = nil @yank_start = new_mark @undo_stack = [] @redo_stack = [] @undoing = false @version = 0 @modified = false @keymap = nil end def modified? @modified end def self.open(file_name, name: File.basename(file_name)) s = File.read(file_name) enc = @@auto_detect_encodings.find { |e| s.force_encoding(e) s.valid_encoding? } Buffer.new(s, name: name, file_name: file_name, file_encoding: enc) end def save if @file_name.nil? raise "file name is not set" end s = to_s case @file_format when :dos s.gsub!(/\n/, "\r\n") when :mac s.gsub!(/\n/, "\r") end File.write(@file_name, s, encoding: @file_encoding) @version += 1 @modified = false end def to_s (@contents[0...@gap_start] + @contents[@gap_end..-1]).force_encoding(Encoding::UTF_8) end def substring(s, e) if s > @gap_start || e <= @gap_start @contents[user_to_gap(s)...user_to_gap(e)] else len = @gap_start - s @contents[user_to_gap(s), len] + @contents[@gap_end, e - s - len] end.force_encoding(Encoding::UTF_8) end def byte_after(location = @point) if location < @gap_start @contents.byteslice(location) else @contents.byteslice(location + gap_size) end end def char_after(location = @point) substring(location, location + UTF8_CHAR_LEN[byte_after(location)]) end def bytesize @contents.bytesize - gap_size end alias size bytesize def point_min 0 end def point_max bytesize end def goto_char(pos) if pos < 0 || pos > size raise RangeError, "Out of buffer" end @column = nil @point = pos end def insert(s, merge_undo = false) pos = @point size = s.bytesize adjust_gap(size) @contents[@point, size] = s.b @marks.each do |m| if m.location > @point m.location += size end end @point = @gap_start += size unless @undoing if merge_undo && @undo_stack.last.is_a?(InsertAction) @undo_stack.last.merge(s) @redo_stack.clear else push_undo(InsertAction.new(self, pos, s)) end end @modified = true @column = nil end def newline indentation = save_point { |saved| beginning_of_line s = @point while /[ \t]/ =~ char_after forward_char end str = substring(s, @point) if end_of_buffer? || char_after == "\n" delete_region(s, @point) end str } insert("\n" + indentation) end def delete_char(n = 1) adjust_gap s = @point pos = get_pos(@point, n) if n > 0 str = substring(s, pos) @gap_end += pos - @point @marks.each do |m| if m.location > @point m.location -= pos - @point end end push_undo(DeleteAction.new(self, s, s, str)) @modified = true elsif n < 0 str = substring(pos, s) @marks.each do |m| if m.location > @point m.location += pos - @point end end @point = @gap_start = pos push_undo(DeleteAction.new(self, s, pos, str)) @modified = true end @column = nil end def backward_delete_char(n = 1) delete_char(-n) end def forward_char(n = 1) @point = get_pos(@point, n) @column = nil end def backward_char(n = 1) forward_char(-n) end def forward_word(n = 1) n.times do while !end_of_buffer? && /\p{Letter}|\p{Number}/ !~ char_after forward_char end while !end_of_buffer? && /\p{Letter}|\p{Number}/ =~ char_after forward_char end end end def backward_word(n = 1) n.times do break if beginning_of_buffer? backward_char while !beginning_of_buffer? && /\p{Letter}|\p{Number}/ !~ char_after backward_char end while !beginning_of_buffer? && /\p{Letter}|\p{Number}/ =~ char_after backward_char end if /\p{Letter}|\p{Number}/ !~ char_after forward_char end end end def next_line if @column column = @column else prev_point = @point beginning_of_line column = Unicode::DisplayWidth.of(substring(@point, prev_point), 2) end end_of_line forward_char s = @point while !end_of_buffer? && byte_after != "\n" && Unicode::DisplayWidth.of(substring(s, @point), 2) < column forward_char end @column = column end def previous_line if @column column = @column else prev_point = @point beginning_of_line column = Unicode::DisplayWidth.of(substring(@point, prev_point), 2) end beginning_of_line backward_char beginning_of_line s = @point while !end_of_buffer? && byte_after != "\n" && Unicode::DisplayWidth.of(substring(s, @point), 2) < column forward_char end @column = column end def beginning_of_buffer @point = 0 end def beginning_of_buffer? @point == 0 end def end_of_buffer @point = bytesize end def end_of_buffer? @point == bytesize end def beginning_of_line while !beginning_of_buffer? && byte_after(@point - 1) != "\n" backward_char end @point end def end_of_line while !end_of_buffer? && byte_after(@point) != "\n" forward_char end @point end def new_mark Mark.new(self, @point).tap { |m| @marks << m } end def point_to_mark(mark) @point = mark.location end def mark_to_point(mark) mark.location = @point end def point_at_mark?(mark) @point == mark.location end def point_before_mark?(mark) @point < mark.location end def point_after_mark?(mark) @point > mark.location end def swap_point_and_mark(mark) @point, mark.location = mark.location, @point end def save_point saved = new_mark column = @column begin yield(saved) ensure point_to_mark(saved) saved.delete @column = column end end def mark if @mark.nil? raise "The mark is not set" end @mark.location end def set_mark(pos = @point) @mark ||= new_mark @mark.location = pos end def copy_region(s = @point, e = mark, append = false) str = s <= e ? substring(s, e) : substring(e, s) if append && !KILL_RING.empty? KILL_RING.current.concat(str) else KILL_RING.push(str) end end def kill_region(s = @point, e = mark, append = false) copy_region(s, e, append) delete_region(s, e) end def delete_region(s = @point, e = mark) save_point do old_pos = @point if s > e s, e = e, s end str = substring(s, e) @point = s adjust_gap @gap_end += e - s @marks.each do |m| if m.location > @point m.location -= e - s end end push_undo(DeleteAction.new(self, old_pos, s, str)) @modified = true end end def kill_line(append = false) save_point do |saved| if end_of_buffer? raise RangeError, "End of buffer" end if char_after == ?\n forward_char else end_of_line end pos = @point point_to_mark(saved) kill_region(@point, pos, append) end end def kill_word(append = false) save_point do |saved| if end_of_buffer? raise RangeError, "End of buffer" end forward_word pos = @point point_to_mark(saved) kill_region(@point, pos, append) end end def insert_for_yank(s) mark_to_point(@yank_start) insert(s) end def yank insert_for_yank(KILL_RING.current) end def yank_pop delete_region(@yank_start.location, @point) insert_for_yank(KILL_RING.current(1)) end def undo if @undo_stack.empty? raise "No further undo information" end action = @undo_stack.pop @undoing = true begin was_modified = @modified action.undo if action.version == @version @modified = false action.version = nil elsif !was_modified action.version = @version end @redo_stack.push(action) ensure @undoing = false end end def redo if @redo_stack.empty? raise "No further redo information" end action = @redo_stack.pop @undoing = true begin was_modified = @modified action.redo if action.version == @version @modified = false action.version = nil elsif !was_modified action.version = @version end @undo_stack.push(action) ensure @undoing = false end end def re_search_forward(s) re = Regexp.new(s) b, e = utf8_re_search(@contents, re, user_to_gap(@point)) if b.nil? raise "Search failed" end if b < @gap_end && e > @gap_start b, e = utf8_re_search(@contents, re, @gap_end) if b.nil? raise "Search failed" end end if /[\x80-\xbf]/n =~ @contents[e] raise "Search failed" end goto_char(gap_to_user(e)) end def transpose_chars if end_of_buffer? || char_after == "\n" backward_char end if beginning_of_buffer? raise RangeError, "Beginning of buffer" end backward_char c = char_after delete_char forward_char insert(c) end private def adjust_gap(min_size = 0) if @gap_start < @point len = user_to_gap(@point) - @gap_end @contents[@gap_start, len] = @contents[@gap_end, len] @gap_start += len @gap_end += len elsif @gap_start > @point len = @gap_start - @point @contents[@gap_end - len, len] = @contents[@point, len] @gap_start -= len @gap_end -= len end if gap_size < min_size new_gap_size = GAP_SIZE + min_size extended_size = new_gap_size - gap_size @contents[@gap_end, 0] = "\0" * extended_size @gap_end += extended_size end end def gap_size @gap_end - @gap_start end def user_to_gap(pos) if pos <= @gap_start pos else gap_size + pos end end def gap_to_user(gpos) if gpos <= @gap_start gpos elsif gpos >= @gap_end gpos - gap_size else raise RangeError, "Position is in gap" end end def get_pos(pos, offset) if offset >= 0 i = offset while i > 0 raise RangeError, "Out of buffer" if end_of_buffer? b = byte_after(pos) pos += UTF8_CHAR_LEN[b] raise RangeError, "Out of buffer" if pos > bytesize i -= 1 end else i = -offset while i > 0 pos -= 1 raise RangeError, "Out of buffer" if pos < 0 while /[\x80-\xbf]/n =~ byte_after(pos) pos -= 1 raise RangeError, "Out of buffer" if pos < 0 end i -= 1 end end pos end def push_undo(action) return if @undoing if @undo_stack.size >= UNDO_LIMIT @undo_stack[0, @undo_stack.size + 1 - UNDO_LIMIT] = [] end if !modified? action.version = @version end @undo_stack.push(action) @redo_stack.clear end def utf8_re_search(s, re, pos) char_pos = s[0...pos].force_encoding(Encoding::UTF_8).size s.force_encoding(Encoding::UTF_8) begin if s.index(re, char_pos) m = Regexp.last_match b = m.pre_match.bytesize e = b + m.to_s.bytesize [b, e] else nil end rescue ArgumentError # invalid byte sequence in UTF-8 nil ensure s.force_encoding(Encoding::ASCII_8BIT) end end end class Mark attr_accessor :location def initialize(buffer, location) @buffer = buffer @location = location end def delete @buffer.marks.delete(self) end end class KillRing def initialize(max = 30) @max = max @ring = [] @current = -1 end def push(str) @current += 1 if @ring.size < @max @ring.insert(@current, str) else if @current == @max @current = 0 end @ring[@current] = str end end def current(n = 0) if @ring.empty? raise "Kill ring is empty" end @current -= n if @current < 0 @current += @ring.size end @ring[@current] end def empty? @ring.empty? end end KILL_RING = KillRing.new class UndoableAction attr_accessor :version def initialize(buffer, location) @version = nil @buffer = buffer @location = location end end class InsertAction < UndoableAction def initialize(buffer, location, string) super(buffer, location) @string = string end def undo @buffer.goto_char(@location) @buffer.delete_char(@string.size) end def redo @buffer.goto_char(@location) @buffer.insert(@string) end def merge(s) @string.concat(s) end end class DeleteAction < UndoableAction def initialize(buffer, location, insert_location, string) super(buffer, location) @insert_location = insert_location @string = string end def undo @buffer.goto_char(@insert_location) @buffer.insert(@string) @buffer.goto_char(@location) end def redo @buffer.goto_char(@insert_location) @buffer.delete_char(@string.size) end end end
module TextualDateTimes #FIXME need to somehow save/recall the textual values, otherwise this breaks on edit/update def method_missing(method_name, *args) if method_name.to_s =~ /(.*)_textual$/ send($1) elsif method_name.to_s =~ /(.*)_textual=$/ send("#{$1}=", Chronic.parse(args.first)) else super end end end fixed textual date update problem module TextualDateTimes def method_missing(method_name, *args) if method_name.to_s =~ /(.*)_textual$/ send($1).strftime "%Y-%m-%d %H:%M" elsif method_name.to_s =~ /(.*)_textual=$/ send("#{$1}=", Chronic.parse(args.first)) else super end end end
#!/usr/bin/env ruby # this file lives at git@git.squareup.com:square/kochiku.git under scripts/clean_nexus_app_releases.rb # RELEASES_DIR = "/app/nexus/sonatype-work/nexus/storage/app-releases" REFS_API_URLS = [ "https://git.squareup.com/api/v3/repos/square/java/git/refs/heads" ] BRANCHES_TO_KEEP = { # mtv-styley: /^ci-(.*)-master\/latest$/ => '\1', /^(.*)-staging\/latest$/ => '\1', /^(.*)-production\/latest$/ => '\1', # hoist I guess? /^deployable-(.*)$/ => '\1', /^hoist\/(.*)\/.*\/staging$/ => '\1', /^hoist\/(.*)\/.*\/production/ => '\1', } HOURS_TO_RETAIN = 12 Dir.chdir RELEASES_DIR puts "Running #{[$0, ARGV].flatten.join(" ")} at #{Time.now.to_s}" puts "" require 'uri' require 'net/http' require 'json' require 'pathname' require 'fileutils' def dump_disk_info(stage) puts "#{stage}: df -h #{RELEASES_DIR}:" system "df -h ." puts "" puts "#{stage}: du -sh #{RELEASES_DIR}:" system "du -sh" puts "" puts "#{stage}: du -sh #{RELEASES_DIR}/com/squareup/*:" system "du -sh com/squareup/*" puts "" end dump_disk_info("before") class GithubRequest def self.get(uri) make_request(:get, uri, []) end private def self.make_request(method, uri, args) body = nil Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| response = http.send(method, uri.path, *args) body = response.body end body end end shas_to_keep = {} REFS_API_URLS.each do |url| ref_infos = JSON.parse(GithubRequest.get(URI.parse(url))) ref_infos.each do |ref_info| branch_name = ref_info["ref"].gsub(/^refs\/heads\//, '') BRANCHES_TO_KEEP.each do |re, replacement| if re =~ branch_name sha = ref_info["object"]["sha"] sha_info = shas_to_keep[sha] ||= { artifacts: {} } (sha_info[:artifacts][branch_name.gsub(re, replacement)] ||= []) << branch_name end end end end puts "We want to retain #{shas_to_keep.size} shas." elderly_shaded_jars = `find . -name .nexus -prune -o -name *-shaded.jar -mmin +#{HOURS_TO_RETAIN * 60}`.split(/\n/) elderly_shaded_jars.each do |jar| jar_file = Pathname(jar) next if jar_file.basename.to_s == ".nexus" sha_dir = jar_file.dirname sha = sha_dir.basename.to_s artifact_name = jar_file.parent.parent.basename.to_s sha_info = shas_to_keep[sha] retain = false if sha_info sha_info[:artifacts].each do |artifact_to_keep, triggering_branches| if artifact_name == artifact_to_keep puts "Retaining #{jar_file} because #{triggering_branches.join(", ")}" retain = true end end end unless retain puts "Removing #{sha_dir}" FileUtils.rm_rf(sha_dir) end end dump_disk_info("after") File.write("clean-info.txt", "Last cleaned by ~nexus/bin/clean_nexus_app_releases.rb at #{`date`.chomp}.") minor updates to clean nexus script #!/usr/bin/env ruby # this file lives at git@git.squareup.com:square/kochiku.git under scripts/clean_nexus_app_releases.rb # RELEASES_DIR = "/app/nexus/sonatype-work/nexus/storage/app-releases" REFS_API_URLS = [ "https://git.squareup.com/api/v3/repos/square/java/git/refs/heads" ] BRANCHES_TO_KEEP = [ # mtv-styley: /^ci-(\w+)-master\/latest$/, /^(\w+)-staging\/latest$/, /^(\w+)-production\/latest$/, # hoist I guess? /^deployable-(\w+)$/, /^hoist\/(\w+)\/\w+\/staging$/, /^hoist\/(\w+)\/\w+\/production/, ] HOURS_TO_RETAIN = 12 Dir.chdir RELEASES_DIR puts "Running #{[$0, ARGV].flatten.join(" ")} at #{Time.now.to_s}" puts "" require 'uri' require 'net/http' require 'json' require 'pathname' require 'fileutils' def dump_disk_info(stage) puts "#{stage}: df -h #{RELEASES_DIR}:" system "df -h ." puts "" puts "#{stage}: du -sh #{RELEASES_DIR}:" system "du -sh" puts "" puts "#{stage}: du -sh #{RELEASES_DIR}/com/squareup/*:" system "du -sh com/squareup/*" puts "" end dump_disk_info("before") class GithubRequest def self.get(uri) make_request(:get, uri, []) end private def self.make_request(method, uri, args) body = nil Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| response = http.send(method, uri.path, *args) body = response.body end body end end shas_to_keep = {} REFS_API_URLS.each do |url| ref_infos = JSON.parse(GithubRequest.get(URI.parse(url))) ref_infos.each do |ref_info| branch_name = ref_info["ref"].gsub(/^refs\/heads\//, '') BRANCHES_TO_KEEP.each do |branch_regexp| branch_regexp.match(branch_name) do |m| sha = ref_info["object"]["sha"] sha_info = shas_to_keep[sha] ||= { artifacts: {} } (sha_info[:artifacts][m[1]] ||= []) << branch_name end end end end puts "We want to retain #{shas_to_keep.size} shas." elderly_shaded_jars = `find . -name .nexus -prune -o -name *-shaded.jar -mmin +#{HOURS_TO_RETAIN * 60}`.split(/\n/) elderly_shaded_jars.each do |jar| jar_file = Pathname(jar) next if jar_file.basename.to_s == ".nexus" sha_dir = jar_file.dirname sha = sha_dir.basename.to_s artifact_name = jar_file.parent.parent.basename.to_s sha_info = shas_to_keep[sha] retain = false if sha_info sha_info[:artifacts].each do |artifact_to_keep, triggering_branches| if artifact_name == artifact_to_keep puts "Retaining #{jar_file} because #{triggering_branches.join(", ")}" retain = true end end end unless retain puts "Removing #{sha_dir}" FileUtils.rm_rf(sha_dir) end end dump_disk_info("after") File.write("clean-info.txt", "Last cleaned by ~nexus/bin/clean_nexus_app_releases.rb at #{`date`.chomp}.")
# -*- coding: utf-8 -*- require 'net/https' require 'json' require 'twitter' require 'redis' require 'date' def download_events(etag) github_oauth_token = ENV['GITHUB_OAUTH_TOKEN'] github_user = ENV['GITHUB_USER'] https = Net::HTTP.new('api.github.com',443) https.use_ssl = true https.start { header = etag.nil? ? {} : {"If-None-Match" => etag} https.get("/users/#{github_user}/received_events?access_token=#{github_oauth_token}", header) } end def to_array(s) JSON.parse(s).map {|json| user = json["actor"]["login"] repo = json["repo"]["name"] type = json["type"].sub(/Event$/, "") content = "#{user}, #{repo}" url = "" payload = json["payload"] case type when "CommitComment" short_type = "[CC]" content = short_type + content url = payload["comment"]["html_url"] when "Create" short_type = "[C]" ref_type = payload["ref_type"] content = short_type + content + "\n#{ref_type}" url = "https://github.com/#{repo}" when "Delete" short_type = "[D]" ref_type = payload["ref_type"] content = short_type + content + "\n#{ref_type}" url = "https://github.com/#{repo}" when "Fork" short_type = "[F]" full_name = payload["forkee"]["full_name"] content = short_type + content + "\n#{full_name}" url = payload["forkee"]["html_url"] when "Gollum" short_type = "[G]" content = short_type + content url = "https://github.com/#{repo}/wiki" when "IssueComment" short_type = "[IC]" issue_title = payload["issue"]["title"] content = short_type + content + "\n\"#{issue_title}\"" url = payload["comment"]["html_url"] when "Issues" short_type = "[I]" action = payload["action"] issue_title = payload["issue"]["title"] content = short_type + content + "\n#{action}\n\"#{issue_title}\"" url = payload["issue"]["html_url"] when "Member" short_type = "[M]" action = payload["action"] acted_user = payload["member"]["login"] content = short_type + content + "\n#{action}\n#{acted_user}" url = "https://github.com/#{repo}" when "PullRequest" short_type = "[PR]" action = payload["action"] title = payload["pull_request"]["title"] content = short_type + content + "\n#{action}\n\"#{title}\"" url = payload["pull_request"]["html_url"] when "PullRequestReviewComment" short_type = "[PRRC]" action = payload["action"] pull_request_title = payload["pull_request"]["title"] content = short_type + content + "\n#{action}\n\"#{pull_request_title}\"" url = payload["comment"]["html_url"] when "Push" short_type = "[P]" before = payload["before"].slice(0, 10) head = payload["head"].slice(0, 10) content = short_type + content url = "https://github.com/#{repo}/compare/#{before}...#{head}" when "Release" short_type = "[R]" action = payload["action"] tag_name = payload["release"]["tag_name"] content = short_type + content + "\n#{action}\n#{tag_name}" url = payload["release"]["html_url"] when "TeamAdd" short_type = "[T]" team_name = payload["team"]["name"] content = short_type + content + "\n#{team_name}" url = "https://github.com/#{repo}" when "Watch" short_type = "[W]" action = payload["action"] content = short_type + content + "\n#{action}" url = "https://github.com/#{repo}" end { content: content, url: url } } end def tweet(content) twitter_consumer_key = ENV['TWITTER_CONSUMER_KEY'] twitter_consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] twitter_access_token = ENV['TWITTER_ACCESS_TOKEN'] twitter_access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET'] client = Twitter::REST::Client.new do |config| config.consumer_key = twitter_consumer_key config.consumer_secret = twitter_consumer_secret config.access_token = twitter_access_token config.access_token_secret = twitter_access_token_secret end client.update(content) end def read_last_etag begin redis.get "event_etag" rescue if File.exist?("event_etag") File.open("event_etag") {|f| f.read } else nil end end end def save_etag(etag) unless etag.nil? begin redis.set "event_etag", etag rescue File.write("event_etag", etag) end end end def redis if ENV["REDISTOGO_URL"].nil? Redis.new host:"127.0.0.1", port:"6379" else uri = URI.parse(ENV["REDISTOGO_URL"]) Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) end end response = download_events(read_last_etag) if response.code.to_i == 200 etag = response['ETag'] events = to_array(response.body).reject{|x| x.nil?} events.each{|entry| url_limit = 23 # t.co length lf_length = 2 # \n length s = if entry[:content].size > (140 - url_limit - lf_length) n = entry[:content].size - (140 - url_limit - lf_length) entry[:content][0, entry[:content].size - n] + "\n" + entry[:url] else entry[:content] + "\n" + entry[:url] end tweet(s) } save_etag(etag) end Implement github api error handling # -*- coding: utf-8 -*- require 'net/https' require 'json' require 'twitter' require 'redis' require 'date' def download_events(etag) github_oauth_token = ENV['GITHUB_OAUTH_TOKEN'] github_user = ENV['GITHUB_USER'] https = Net::HTTP.new('api.github.com',443) https.use_ssl = true https.start { header = etag.nil? ? {} : {"If-None-Match" => etag} https.get("/users/#{github_user}/received_events?access_token=#{github_oauth_token}", header) } end def to_array(s) JSON.parse(s).map {|json| user = json["actor"]["login"] repo = json["repo"]["name"] type = json["type"].sub(/Event$/, "") content = "#{user}, #{repo}" url = "" payload = json["payload"] case type when "CommitComment" short_type = "[CC]" content = short_type + content url = payload["comment"]["html_url"] when "Create" short_type = "[C]" ref_type = payload["ref_type"] content = short_type + content + "\n#{ref_type}" url = "https://github.com/#{repo}" when "Delete" short_type = "[D]" ref_type = payload["ref_type"] content = short_type + content + "\n#{ref_type}" url = "https://github.com/#{repo}" when "Fork" short_type = "[F]" full_name = payload["forkee"]["full_name"] content = short_type + content + "\n#{full_name}" url = payload["forkee"]["html_url"] when "Gollum" short_type = "[G]" content = short_type + content url = "https://github.com/#{repo}/wiki" when "IssueComment" short_type = "[IC]" issue_title = payload["issue"]["title"] content = short_type + content + "\n\"#{issue_title}\"" url = payload["comment"]["html_url"] when "Issues" short_type = "[I]" action = payload["action"] issue_title = payload["issue"]["title"] content = short_type + content + "\n#{action}\n\"#{issue_title}\"" url = payload["issue"]["html_url"] when "Member" short_type = "[M]" action = payload["action"] acted_user = payload["member"]["login"] content = short_type + content + "\n#{action}\n#{acted_user}" url = "https://github.com/#{repo}" when "PullRequest" short_type = "[PR]" action = payload["action"] title = payload["pull_request"]["title"] content = short_type + content + "\n#{action}\n\"#{title}\"" url = payload["pull_request"]["html_url"] when "PullRequestReviewComment" short_type = "[PRRC]" action = payload["action"] pull_request_title = payload["pull_request"]["title"] content = short_type + content + "\n#{action}\n\"#{pull_request_title}\"" url = payload["comment"]["html_url"] when "Push" short_type = "[P]" before = payload["before"].slice(0, 10) head = payload["head"].slice(0, 10) content = short_type + content url = "https://github.com/#{repo}/compare/#{before}...#{head}" when "Release" short_type = "[R]" action = payload["action"] tag_name = payload["release"]["tag_name"] content = short_type + content + "\n#{action}\n#{tag_name}" url = payload["release"]["html_url"] when "TeamAdd" short_type = "[T]" team_name = payload["team"]["name"] content = short_type + content + "\n#{team_name}" url = "https://github.com/#{repo}" when "Watch" short_type = "[W]" action = payload["action"] content = short_type + content + "\n#{action}" url = "https://github.com/#{repo}" end { content: content, url: url } } end def tweet(content) twitter_consumer_key = ENV['TWITTER_CONSUMER_KEY'] twitter_consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] twitter_access_token = ENV['TWITTER_ACCESS_TOKEN'] twitter_access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET'] client = Twitter::REST::Client.new do |config| config.consumer_key = twitter_consumer_key config.consumer_secret = twitter_consumer_secret config.access_token = twitter_access_token config.access_token_secret = twitter_access_token_secret end client.update(content) end def read_last_etag begin redis.get "event_etag" rescue if File.exist?("event_etag") File.open("event_etag") {|f| f.read } else nil end end end def save_etag(etag) unless etag.nil? begin redis.set "event_etag", etag rescue File.write("event_etag", etag) end end end def redis if ENV["REDISTOGO_URL"].nil? Redis.new host:"127.0.0.1", port:"6379" else uri = URI.parse(ENV["REDISTOGO_URL"]) Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) end end response = download_events(read_last_etag) if response.code.to_i == 200 etag = response['ETag'] events = to_array(response.body).reject{|x| x.nil?} events.each{|entry| url_limit = 23 # t.co length lf_length = 2 # \n length s = if entry[:content].size > (140 - url_limit - lf_length) n = entry[:content].size - (140 - url_limit - lf_length) entry[:content][0, entry[:content].size - n] + "\n" + entry[:url] else entry[:content] + "\n" + entry[:url] end tweet(s) } save_etag(etag) elsif response.code.to_i != 304 raise "GitHub API Error. http_status_code: #{response.code}" end
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false config.cache_store = :mem_cache_store do not use memcached in development environment # Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false
# frozen_string_literal: true Rails.application.configure do # Verifies that versions and hashed value of the package contents in the project's package.json config.webpacker.check_yarn_integrity = false # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp", "caching-dev.txt").exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = false # Suppress logger output for asset requests. config.assets.quiet = true # Prepend all log lines with the following tags. config.log_tags = [:host, :request_id] # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker # ActionMailer host options & delivery through Mailcatcher app_host = ENV.fetch("HOST") { "gobierto.test" } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: ENV.fetch("MAILCATCHER_HOST") { "localhost" }, port: 1025 } config.action_mailer.default_url_options = { host: app_host, script_name: "" } config.action_mailer.asset_host = "http://#{app_host}" config.action_mailer.perform_deliveries = true end yarn integrity dev true # frozen_string_literal: true Rails.application.configure do # Verifies that versions and hashed value of the package contents in the project's package.json config.webpacker.check_yarn_integrity = true # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp", "caching-dev.txt").exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = false # Suppress logger output for asset requests. config.assets.quiet = true # Prepend all log lines with the following tags. config.log_tags = [:host, :request_id] # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker # ActionMailer host options & delivery through Mailcatcher app_host = ENV.fetch("HOST") { "gobierto.test" } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: ENV.fetch("MAILCATCHER_HOST") { "localhost" }, port: 1025 } config.action_mailer.default_url_options = { host: app_host, script_name: "" } config.action_mailer.asset_host = "http://#{app_host}" config.action_mailer.perform_deliveries = true end
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Action Mailer settings config.action_mailer.delivery_method = :smtp config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } # Config for mailcatcher https://mailcatcher.me/ config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025, :locale => 'fr' } Rails.application.routes.default_url_options = { host: 'localhost:3000', protocol: :http } # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.action_cable.url = "ws://localhost:3000/cable" end Config: add action_mailer.asset_host var to send image in email Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Action Mailer settings config.action_mailer.delivery_method = :smtp config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } config.action_mailer.asset_host = 'http://localhost:3000' # Config for mailcatcher https://mailcatcher.me/ config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025, :locale => 'fr' } Rails.application.routes.default_url_options = { host: 'localhost:3000', protocol: :http } # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.action_cable.url = "ws://localhost:3000/cable" end
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # config.autoload_paths << Rails.root.join('app') config.read_encrypted_secrets = true # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false config.eager_load_paths += ["#{Rails.root}/lib"] # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=172800' } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. # config.assets.debug = true # Suppress logger output for asset requests. # config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker config.web_console.whitelisted_ips = '192.168.0.0/16' end Remove ActionMailer configuration since railtie is disabled Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # config.autoload_paths << Rails.root.join('app') config.read_encrypted_secrets = true # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false config.eager_load_paths += ["#{Rails.root}/lib"] # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=172800' } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. # config.action_mailer.raise_delivery_errors = false # config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. # config.assets.debug = true # Suppress logger output for asset requests. # config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker config.web_console.whitelisted_ips = '192.168.0.0/16' end
Wripe::Application.configure do # Settings specified here will take precedence over those in config/application.rb. app_base = URI.new(ENV['APP_BASE'] || 'https://wri.pe') Rails.application.routes.default_url_options = { protocol: app_base.protocol, host: app_base.host } # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. config.assets.debug = true end fix development default_url_options Wripe::Application.configure do # Settings specified here will take precedence over those in config/application.rb. app_base = URI(ENV['APP_BASE'] || 'https://wri.pe') Rails.application.routes.default_url_options = { protocol: app_base.scheme, host: app_base.host } # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. config.assets.debug = true end
# -*- encoding : utf-8 -*- Otwartezabytki::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true # Use mailcatcher for debugging e-mails config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 } config.action_mailer.default_url_options = { :host => "otwartezabytki.dev" } end assets.debug = false # -*- encoding : utf-8 -*- Otwartezabytki::Application.configure do # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Raise exception on mass assignment protection for Active Record models config.active_record.mass_assignment_sanitizer = :strict # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) config.active_record.auto_explain_threshold_in_seconds = 0.5 # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = false # Use mailcatcher for debugging e-mails config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 } config.action_mailer.default_url_options = { :host => "otwartezabytki.dev" } end
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=172800' } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end TimeZone en desarrollo cambiado a Buenos Aires Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=172800' } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker config.time_zone = "America/Argentina/Buenos_Aires" end
Gfw::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true config.action_dispatch.default_headers = { 'X-Frame-Options' => 'ALLOWALL' } end don't debug assets in production Gfw::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = false config.action_dispatch.default_headers = { 'X-Frame-Options' => 'ALLOWALL' } end
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end Usando mailcatcher Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = {address: 'localhost', port: 1025 } end
Agrosocial::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. # Uncomment the next line #config.consider_all_requests_local = true config.consider_all_requests_local = false # and comment this one config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = true # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # email configuration config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: "smtp.gmail.com", port: 587, domain: "gmail.com", authentication: "plain", enable_starttls_auto: true, user_name: "agro.social2", password: "agrosocial2" } end Disabl Dynamic errors pages Agrosocial::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. # Uncomment the next line config.consider_all_requests_local = true #config.consider_all_requests_local = false # and comment this one config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = true # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # email configuration config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: "smtp.gmail.com", port: 587, domain: "gmail.com", authentication: "plain", enable_starttls_auto: true, user_name: "agro.social2", password: "agrosocial2" } end
Contacts::Application.configure do require "#{config.root}/spec/support/mock_organisations_api" require "#{config.root}/spec/support/fake_rummageable_index" # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true config.assets.prefix = "/assets" config.after_initialize do Contacts.enable_admin_routes = true Contacts.worldwide_api = GdsApi::Worldwide.new( Plek.current.find('whitehall-admin') ) Contacts.rummager_client = if ENV['RUMMAGER_API'] Rummageable::Index.new( Plek.current.find('search'), 'mainstream', logger: Rails.logger ) else FakeRummageableIndex.new("http://localhost", 'mainstream', logger: Rails.logger) end end end Configure asset host in development mode. When run under `govuk_setenv`, this configures the asset_host to point at the assets-origin on the dev VM. This will give us better dev-prod parity, and enable running this behind the router in dev. This also removes the override of the assets prefix in development. There shouldn't be a need to override this. Contacts::Application.configure do require "#{config.root}/spec/support/mock_organisations_api" require "#{config.root}/spec/support/fake_rummageable_index" # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true if ENV['GOVUK_ASSET_ROOT'].present? config.asset_host = ENV['GOVUK_ASSET_ROOT'] end config.after_initialize do Contacts.enable_admin_routes = true Contacts.worldwide_api = GdsApi::Worldwide.new( Plek.current.find('whitehall-admin') ) Contacts.rummager_client = if ENV['RUMMAGER_API'] Rummageable::Index.new( Plek.current.find('search'), 'mainstream', logger: Rails.logger ) else FakeRummageableIndex.new("http://localhost", 'mainstream', logger: Rails.logger) end end end
ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'tie', 'ties' end source files should end with a newline (\n). ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'tie', 'ties' end
class Rack::Attack heavy = ['/api/v1/groups', '/api/v1/invitations/bulk_create'] # considerations # multiple users could be using same ip address (eg coworking space) # does not distinguish between valid and invalid requests (eg: form validation) # - so we need to allow for errors and resubmits without interruption. # our attackers seem to create a group every 1 or 2 minutes, each with max invitations. # so we're mostly interested in the hour and day limits # group creation and invitation sending is the most common attack we see # usually we get a few new groups per hour, globally. # when attacks happen we see a few groups per minute, usually with the same name # each trying to invite max_invitations with bulk create. {10 => 1.hour, 20 => 1.day}.each_pair do |limit, period| Rack::Attack.throttle("groups#create", :limit => limit, :period => period) do |req| puts "testing #{req}" req.ip if heavy.any? {|route| req.path.starts_with?(route)} && req.post? end end medium = ['login_tokens', 'invitations', 'discussions', 'polls', 'stances', 'comments', 'reactions', 'attachments', 'registrations', 'contact_messages'] # throttles all posts to the above endponts # so we're looking at a record creation attack. # the objective of these rules is not to guess what normal behaviour looks like # and pitch abouve that.. but to identify what abusive behaviour certainly is, # and ensure it cannot get really really bad. {100 => 5.minutes, 1000 => 1.hour, 10000 => 1.day}.each_pair do |limit, period| Rack::Attack.throttle("record#create", :limit => limit, :period => period) do |req| req.ip if medium.any? {|route| req.path.starts_with?("/api/v1/#{route}")} && req.post? end end end remote puts class Rack::Attack heavy = ['/api/v1/groups', '/api/v1/invitations/bulk_create'] # considerations # multiple users could be using same ip address (eg coworking space) # does not distinguish between valid and invalid requests (eg: form validation) # - so we need to allow for errors and resubmits without interruption. # our attackers seem to create a group every 1 or 2 minutes, each with max invitations. # so we're mostly interested in the hour and day limits # group creation and invitation sending is the most common attack we see # usually we get a few new groups per hour, globally. # when attacks happen we see a few groups per minute, usually with the same name # each trying to invite max_invitations with bulk create. {10 => 1.hour, 20 => 1.day}.each_pair do |limit, period| Rack::Attack.throttle("groups#create", :limit => limit, :period => period) do |req| req.ip if heavy.any? {|route| req.path.starts_with?(route)} && req.post? end end medium = ['login_tokens', 'invitations', 'discussions', 'polls', 'stances', 'comments', 'reactions', 'attachments', 'registrations', 'contact_messages'] # throttles all posts to the above endponts # so we're looking at a record creation attack. # the objective of these rules is not to guess what normal behaviour looks like # and pitch abouve that.. but to identify what abusive behaviour certainly is, # and ensure it cannot get really really bad. {100 => 5.minutes, 1000 => 1.hour, 10000 => 1.day}.each_pair do |limit, period| Rack::Attack.throttle("record#create", :limit => limit, :period => period) do |req| req.ip if medium.any? {|route| req.path.starts_with?("/api/v1/#{route}")} && req.post? end end end
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttled_response = ->(env) { [429, {}, [ActionView::Base.new.render(file: 'public/429.html')]] } ActiveSupport::Notifications.subscribe('rack.attack') do |name, start, finish, request_id, req| Airbrake.notify Exception.new "#{req.ip} has been rate limited for url #{req.url}" end @config = YAML.load_file("#{Rails.root}/config/rack_attack.yml").with_indifferent_access def from_config(key, field) @config[key][field] || @config[:default][field] end def throttle_request?(key, req) from_config(key, :method) == req.env['REQUEST_METHOD'] && /#{from_config(key, :path)}/.match(req.path.to_s) end @config.keys.each do |key| Rack::Attack.throttle key, limit: from_config(key, :limit), period: from_config(key, :period) do |req| req.ip if throttle_request? key, req end unless key == 'default' end Add throttling data for airbrake exception Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new Rack::Attack.throttled_response = ->(env) { [429, {}, [ActionView::Base.new.render(file: 'public/429.html')]] } ActiveSupport::Notifications.subscribe('rack.attack') do |name, start, finish, request_id, req| Airbrake.notify Exception.new(message: "#{req.ip} has been rate limited for url #{req.url}", data: req.env['rack.attack.throttle_data']) end @config = YAML.load_file("#{Rails.root}/config/rack_attack.yml").with_indifferent_access def from_config(key, field) @config[key][field] || @config[:default][field] end def throttle_request?(key, req) from_config(key, :method) == req.env['REQUEST_METHOD'] && /#{from_config(key, :path)}/.match(req.path.to_s) end @config.keys.each do |key| Rack::Attack.throttle key, limit: from_config(key, :limit), period: from_config(key, :period) do |req| req.ip if throttle_request? key, req end unless key == 'default' end
[ RailsAdmin::Config::Actions::DiskUsage, RailsAdmin::Config::Actions::SendToFlow, RailsAdmin::Config::Actions::SwitchNavigation, RailsAdmin::Config::Actions::DataType, RailsAdmin::Config::Actions::Import, #RailsAdmin::Config::Actions::EdiExport, RailsAdmin::Config::Actions::ImportSchema, RailsAdmin::Config::Actions::DeleteAll, RailsAdmin::Config::Actions::TranslatorUpdate, RailsAdmin::Config::Actions::Convert, RailsAdmin::Config::Actions::SimpleShare, RailsAdmin::Config::Actions::BulkShare, RailsAdmin::Config::Actions::Pull, RailsAdmin::Config::Actions::RetryTask, RailsAdmin::Config::Actions::DownloadFile, RailsAdmin::Config::Actions::ProcessFlow, RailsAdmin::Config::Actions::BuildGem, RailsAdmin::Config::Actions::Run, RailsAdmin::Config::Actions::Authorize, RailsAdmin::Config::Actions::SimpleDeleteDataType, RailsAdmin::Config::Actions::BulkDeleteDataType, RailsAdmin::Config::Actions::SimpleGenerate, RailsAdmin::Config::Actions::BulkGenerate, RailsAdmin::Config::Actions::SimpleExpand, RailsAdmin::Config::Actions::BulkExpand, RailsAdmin::Config::Actions::Records, RailsAdmin::Config::Actions::SwitchScheduler, RailsAdmin::Config::Actions::SimpleExport, RailsAdmin::Config::Actions::Schedule, RailsAdmin::Config::Actions::Submit, RailsAdmin::Config::Actions::Trash, RailsAdmin::Config::Actions::Inspect, RailsAdmin::Config::Actions::Copy, RailsAdmin::Config::Actions::Cancel, RailsAdmin::Config::Actions::Configure, RailsAdmin::Config::Actions::SimpleCrossShare, RailsAdmin::Config::Actions::BulkCrossShare, RailsAdmin::Config::Actions::Regist, RailsAdmin::Config::Actions::SharedCollectionIndex, RailsAdmin::Config::Actions::BulkPull, RailsAdmin::Config::Actions::CleanUp, RailsAdmin::Config::Actions::ShowRecords, RailsAdmin::Config::Actions::RunScript, RailsAdmin::Config::Actions::Play, RailsAdmin::Config::Actions::PullImport, RailsAdmin::Config::Actions::State, RailsAdmin::Config::Actions::Documentation, RailsAdmin::Config::Actions::Push ].each { |a| RailsAdmin::Config::Actions.register(a) } RailsAdmin::Config::Actions.register(:export, RailsAdmin::Config::Actions::BulkExport) [ RailsAdmin::Config::Fields::Types::JsonValue, RailsAdmin::Config::Fields::Types::JsonSchema, RailsAdmin::Config::Fields::Types::StorageFile, RailsAdmin::Config::Fields::Types::EnumEdit, RailsAdmin::Config::Fields::Types::Model, RailsAdmin::Config::Fields::Types::Record, RailsAdmin::Config::Fields::Types::HtmlErb, RailsAdmin::Config::Fields::Types::OptionalBelongsTo ].each { |f| RailsAdmin::Config::Fields::Types.register(f) } RailsAdmin::Config::Fields::Types::CodeMirror.register_instance_option :js_location do bindings[:view].asset_path('codemirror.js') end RailsAdmin::Config::Fields::Types::CodeMirror.register_instance_option :css_location do bindings[:view].asset_path('codemirror.css') end RailsAdmin::Config::Fields::Types::CodeMirror.register_instance_option :config do { mode: 'css', theme: 'neo', } end RailsAdmin::Config::Fields::Types::CodeMirror.register_instance_option :assets do { mode: bindings[:view].asset_path('codemirror/modes/css.js'), theme: bindings[:view].asset_path('codemirror/themes/neo.css'), } end module RailsAdmin module Config class << self def navigation(label, options) navigation_options[label.to_s] = options end def navigation_options @nav_options ||= {} end end end end RailsAdmin.config do |config| config.total_columns_width = 900 ## == PaperTrail == # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration config.authenticate_with do warden.authenticate! scope: :user unless %w(dashboard shared_collection_index index show).include?(action_name) end config.current_user_method { current_user } config.audit_with :mongoid_audit config.authorize_with :cancan config.excluded_models += [Setup::BaseOauthAuthorization, Setup::AwsAuthorization] config.actions do dashboard # mandatory # disk_usage shared_collection_index index # mandatory new { except [Setup::Event, Setup::DataType, Setup::Authorization, Setup::BaseOauthProvider] } import import_schema pull_import translator_update convert export bulk_delete show show_records run run_script edit configure play copy simple_share bulk_share simple_cross_share bulk_cross_share build_gem pull bulk_pull push download_file process_flow authorize simple_generate bulk_generate simple_expand bulk_expand records switch_navigation switch_scheduler simple_export schedule state retry_task submit inspect cancel regist simple_delete_data_type bulk_delete_data_type delete trash clean_up #show_in_app send_to_flow delete_all data_type #history_index history_show do only do [ Setup::Algorithm, Setup::Connection, Setup::Webhook, Setup::Translator, Setup::Flow, Setup::OauthClient, Setup::Oauth2Scope ] + Setup::DataType.class_hierarchy + Setup::Validator.class_hierarchy + Setup::BaseOauthProvider.class_hierarchy end visible { only.include?((obj = bindings[:object]).class) && obj.try(:shared?) } end documentation end def shared_read_only instance_eval do read_only { (obj = bindings[:object]).creator_id != User.current.id && obj.shared? } end end shared_non_editable = Proc.new do shared_read_only end #Collections config.navigation 'Collections', icon: 'fa fa-cubes' config.model Setup::CrossCollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CrossCollectionPullParameter do visible false object_label_method { :label } configure :location, :json_value edit do field :label field :property_name field :location end show do field :label field :property_name field :location field :created_at #field :creator field :updated_at end fields :label, :property_name, :location end config.model Setup::CrossSharedCollection do weight 000 label 'Cross Shared Collection' navigation_label 'Collections' object_label_method :versioned_name visible { Account.current_super_admin? } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' configure :readme, :html_erb configure :pull_data, :json_value configure :data, :json_value configure :swagger_spec, :json_value group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :image field :logo_background, :color field :name field :shared_version field :summary field :category field :authors field :pull_count field :pull_parameters field :dependencies field :readme end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary field :readme field :authors field :pull_count field :_id field :updated_at field :data_schemas do label 'Schemas' group :data end field :data_custom_validators do label 'Validators' group :data end field :data_data_types do label 'Data Types' group :data end field :data_connections do label 'Connections' group :api_connectors end field :data_webhooks do label 'Webhooks' group :api_connectors end field :data_connection_roles do label 'Connection Roles' group :api_connectors end field :data_flows do label 'Flows' group :workflows end field :data_events do label 'Events' group :workflows end field :data_translators do label 'Translators' group :workflows end field :data_algorithms do label 'Algorithms' group :workflows end field :data_applications do label 'Applications' group :workflows end field :data_authorizations do label 'Autorizations' group :security end field :data_oauth_clients do label 'OAuth Clients' group :security end field :data_oauth_providers do label 'OAuth Providers' group :security end field :data_oauth2_scopes do label 'OAuth 2.0 Scopes' group :security end field :data_namespaces do label 'Namespaces' group :config end end end config.model Setup::SharedCollection do weight 010 label 'Shared Collection' register_instance_option(:discard_submit_buttons) do !(a = bindings[:action]) || a.key != :edit end navigation_label 'Collections' object_label_method { :versioned_name } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' group :collections group :workflows group :api_connectors do label 'Connectors' active true end group :data group :security edit do field :image do visible { !bindings[:object].instance_variable_get(:@sharing) } end field :logo_background field :name do required { true } end field :shared_version do required { true } end field :authors field :summary field :source_collection do visible { !((source_collection = bindings[:object].source_collection) && source_collection.new_record?) } inline_edit false inline_add false associated_collection_scope do source_collection = (obj = bindings[:object]).source_collection Proc.new { |scope| if obj.new_record? scope.where(id: source_collection ? source_collection.id : nil) else scope end } end end field :connections do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_connections)).nil? || v) end help do nil end pretty_value do if bindings[:object].connections.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[connection_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No connection selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && obj.source_collection && obj.source_collection.connections.present? end associated_collection_scope do source_collection = bindings[:object].source_collection connections = (source_collection && source_collection.connections) || [] Proc.new { |scope| scope.any_in(id: connections.collect { |connection| connection.id }) } end end field :dependencies do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_dependencies)).nil? || v) end help do nil end pretty_value do if bindings[:object].dependencies.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[dependency_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No dependencies selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) end end field :pull_parameters field :pull_count do visible { Account.current_super_admin? } end field :readme do visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && !obj.instance_variable_get(:@_selecting_connections) end end end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary do pretty_value do value.html_safe end end field :readme, :html_erb field :authors field :dependencies field :pull_count field :data_namespaces do group :collections label 'Namespaces' list_fields do %w(name slug) end end field :data_flows do group :workflows label 'Flows' list_fields do %w(namespace name) #TODO Inlude a description field on Flow model end end field :data_translators do group :workflows label 'Translators' list_fields do %w(namespace name type style) end end field :data_events do group :workflows label 'Events' list_fields do %w(namespace name _type) end end field :data_algorithms do group :workflows label 'Algorithms' list_fields do %w(namespace name description) end end field :data_connection_roles do group :api_connectors label 'Connection roles' list_fields do %w(namespace name) end end field :data_webhooks do group :api_connectors label 'Webhooks' list_fields do %w(namespace name path method description) end end field :data_connections do group :api_connectors label 'Connections' list_fields do %w(namespace name url) end end field :data_data_types do group :data label 'Data types' list_fields do %w(title name slug _type) end end field :data_schemas do group :data label 'Schemas' list_fields do %w(namespace uri) end end field :data_custom_validators do group :data label 'Custom validators' list_fields do %w(namespace name _type) #TODO Include a description field for Custom Validator model end end # field :data_data TODO Include collection data field field :data_authorizations do group :security label 'Authorizations' list_fields do %w(namespace name _type) end end field :data_oauth_providers do group :security label 'OAuth providers' list_fields do %w(namespace name response_type authorization_endpoint token_endpoint token_method _type) end end field :data_oauth_clients do group :security label 'OAuth clients' list_fields do %w(provider name) end end field :data_oauth2_scopes do group :security label 'OAuth 2.0 scopes' list_fields do %w(provider name description) end end field :_id field :updated_at end list do field :image do thumb_method :icon end field :name do pretty_value do bindings[:object].versioned_name end end field :authors field :summary field :pull_count field :dependencies end end config.model Setup::CollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CollectionPullParameter do visible false object_label_method { :label } field :label field :parameter, :enum do enum do bindings[:controller].instance_variable_get(:@shared_parameter_enum) || [bindings[:object].parameter] end end edit do field :label field :parameter field :property_name field :location, :json_value end show do field :label field :parameter field :created_at #field :creator field :updated_at end list do field :label field :parameter field :updated_at end fields :label, :parameter end config.model Setup::CollectionData do visible false object_label_method { :label } end config.model Setup::Collection do weight 020 navigation_label 'Collections' register_instance_option :label_navigation do 'My Collections' end group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :image field :readme do visible { Account.current_super_admin? } end field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data end show do field :image field :readme, :html_erb field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data field :namespaces field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :image do thumb_method :icon end field :name field :flows do pretty_value do value.count > 0 ? value.count : '-' end end field :connection_roles do pretty_value do value.count > 0 ? value.count : '-' end end field :translators do pretty_value do value.count > 0 ? value.count : '-' end end field :events do pretty_value do value.count > 0 ? value.count : '-' end end field :data_types do pretty_value do value.count > 0 ? value.count : '-' end end field :schemas do pretty_value do value.count > 0 ? value.count : '-' end end field :custom_validators do pretty_value do value.count > 0 ? value.count : '-' end end field :algorithms do pretty_value do value.count > 0 ? value.count : '-' end end field :applications do pretty_value do value.count > 0 ? value.count : '-' end end field :webhooks do pretty_value do value.count > 0 ? value.count : '-' end end field :connections do pretty_value do value.count > 0 ? value.count : '-' end end field :authorizations do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_providers do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_clients do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth2_scopes do pretty_value do value.count > 0 ? value.count : '-' end end field :data field :updated_at end end #Definitions config.navigation 'Definitions', icon: 'fa fa-puzzle-piece' config.model Setup::Validator do navigation_label 'Definitions' label 'Validators' weight 100 fields :namespace, :name fields :namespace, :name, :updated_at show_in_dashboard false end config.model Setup::CustomValidator do visible false configure :_type do pretty_value do value.split('::').last.to_title end end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Schema do weight 101 object_label_method { :custom_title } edit do field :namespace, :enum_edit do read_only { !bindings[:object].new_record? } end field :uri do read_only { !bindings[:object].new_record? } html_attributes do { cols: '74', rows: '1' } end end field :schema, :code_mirror do html_attributes do { cols: '74', rows: '15' } end end field :schema_data_type do inline_edit false inline_add false end end show do field :namespace field :uri field :schema do pretty_value do v = if json = JSON.parse(value) rescue nil "<code class='json'>#{JSON.pretty_generate(json).gsub('<', '&lt;').gsub('>', '&gt;')}</code>" elsif (xml = Nokogiri::XML(value)).errors.blank? "<code class='xml'>#{xml.to_xml.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else "<code>#{value}</code>" end "<pre>#{v}</pre>".html_safe end end field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :uri, :schema_data_type, :updated_at end config.model Setup::XsltValidator do parent Setup::Validator weight 102 label 'XSLT Validator' object_label_method { :custom_title } list do field :namespace field :xslt field :updated_at end fields :namespace, :name, :xslt, :updated_at end config.model Setup::EdiValidator do parent Setup::Validator weight 103 object_label_method { :custom_title } label 'EDI Validator' edit do field :namespace, :enum_edit field :name field :schema_data_type field :content_type end fields :namespace, :name, :schema_data_type, :content_type, :updated_at end config.model Setup::AlgorithmValidator do parent Setup::Validator weight 104 label 'Algorithm Validator' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :algorithm end fields :namespace, :name, :algorithm, :updated_at end config.model Setup::DataType do navigation_label 'Definitions' weight 110 label 'Data Type' object_label_method { :custom_title } visible true show_in_dashboard false configure :_type do pretty_value do value.split('::').last.to_title end end group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :slug configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :title, :enum_edit, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::DataType.fields[:used_memory.to_s].type.new(Setup::DataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::DataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :name field :title field :slug field :_type field :storage_size field :schema do pretty_value do v = if json = JSON.pretty_generate(value) rescue nil "<code class='json'>#{json.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else value end "<pre>#{v}</pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :_type, :storage_size, :updated_at end config.model Setup::JsonDataType do navigation_label 'Definitions' weight 111 label 'JSON Data Type' object_label_method { :custom_title } group :behavior do label 'Behavior' active false end configure :title configure :name do read_only { !bindings[:object].new_record? } end configure :schema, :code_mirror do html_attributes do { cols: '74', rows: '15' } end # pretty_value do # "<pre><code class='json'>#{JSON.pretty_generate(value)}</code></pre>".html_safe # end end configure :storage_size, :decimal do pretty_value do if (objects = bindings[:controller].instance_variable_get(:@objects)) unless (max = bindings[:controller].instance_variable_get(:@max_storage_size)) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :schema, :json_schema do shared_read_only help { 'Required' } end field :title, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless (max = bindings[:controller].instance_variable_get(:@max_used_memory)) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :title field :name field :slug field :storage_size field :schema do pretty_value do "<pre><code class='ruby'>#{JSON.pretty_generate(value)}</code></pre>".html_safe end end field :before_save_callbacks field :records_methods field :data_type_methods field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end config.model Setup::FileDataType do navigation_label 'Definitions' weight 112 label 'File Data Type' object_label_method { :custom_title } group :content do label 'Content' end group :behavior do label 'Behavior' active false end configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :validators do group :content inline_add false end configure :schema_data_type do group :content inline_add false inline_edit false end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :title, &shared_non_editable field :slug field :validators, &shared_non_editable field :schema_data_type, &shared_non_editable field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :validators field :schema_data_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :title field :name field :slug field :validators field :storage_size field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end #Connectors config.navigation 'Connectors', icon: 'fa fa-plug' config.model Setup::Parameter do visible false object_label_method { :to_s } configure :metadata, :json_value configure :value edit do field :name field :value field :description field :metadata end list do field :name field :value field :description field :metadata field :updated_at end end config.model Setup::Connection do navigation_label 'Connectors' weight 200 object_label_method { :custom_title } group :credentials do label 'Credentials' end configure :number, :string do label 'Key' html_attributes do { maxlength: 30, size: 30 } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :token, :text do html_attributes do { cols: '50', rows: '1' } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:url, &shared_non_editable) field :number field :token field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :url field :number field :token field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at field :updated_at end list do field :namespace field :name field :url field :number field :token field :authorization field :updated_at end fields :namespace, :name, :url, :number, :token, :authorization, :updated_at end config.model Setup::ConnectionRole do navigation_label 'Connectors' weight 210 label 'Connection Role' object_label_method { :custom_title } configure :name, :string do help 'Requiered.' html_attributes do { maxlength: 50, size: 50 } end end configure :webhooks do nested_form false end configure :connections do nested_form false end modal do field :namespace, :enum_edit field :name field :webhooks field :connections end show do field :namespace field :name field :webhooks field :connections field :_id field :created_at #field :creator field :updated_at #field :updater end edit do field :namespace, :enum_edit field :name field :webhooks field :connections end fields :namespace, :name, :webhooks, :connections, :updated_at end config.model Setup::Webhook do navigation_label 'Connectors' weight 220 object_label_method { :custom_title } configure :metadata, :json_value group :credentials do label 'Credentials' end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :path, :string do help 'Requiered. Path of the webhook relative to connection URL.' html_attributes do { maxlength: 255, size: 100 } end end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:path, &shared_non_editable) field(:method, &shared_non_editable) field(:description, &shared_non_editable) field(:metadata, :json_value, &shared_non_editable) field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :path field :method field :description field :metadata, :json_value field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :path, :method, :description, :authorization, :updated_at end #Security config.navigation 'Security', icon: 'fa fa-shield' config.model Setup::OauthClient do navigation_label 'Security' label 'OAuth Client' weight 300 object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :identifier do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :secret do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end fields :provider, :name, :identifier, :secret, :tenant, :updated_at end config.model Setup::BaseOauthProvider do navigation_label 'Security' weight 310 object_label_method { :custom_title } label 'Provider' configure :_type do pretty_value do value.split('::').last.to_title end end configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :namespace, :enum_edit list do field :namespace field :name field :_type field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :tenant field :updated_at end fields :namespace, :name, :_type, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :tenant end config.model Setup::OauthProvider do weight 311 label 'OAuth 1.0 provider' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit, &shared_non_editable field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :request_token_endpoint field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :request_token_endpoint, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Provider do weight 312 label 'OAuth 2.0 provider' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :scope_separator field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :scope_separator, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Scope do navigation_label 'Security' weight 320 label 'OAuth 2.0 Scope' object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end fields :provider, :name, :description, :tenant, :updated_at end config.model Setup::Authorization do navigation_label 'Security' weight 330 object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name field :metadata end fields :namespace, :name, :status, :_type, :metadata, :updated_at show_in_dashboard false end config.model Setup::BasicAuthorization do weight 331 register_instance_option :label_navigation do 'Basic' end object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value edit do field :namespace field :name field :username field :password field :metadata end group :credentials do label 'Credentials' end configure :username do group :credentials end configure :password do group :credentials end show do field :namespace field :name field :status field :username field :password field :metadata field :_id end edit do field :namespace, :enum_edit field :name field :username field :password end fields :namespace, :name, :status, :username, :password, :updated_at end config.model Setup::OauthAuthorization do weight 332 label 'OAuth 1.0 authorization' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace, :enum_edit field :name field :client field :parameters field :template_parameters field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :access_token_secret do group :credentials end configure :realm_id do group :credentials end show do field :namespace field :name field :status field :client field :parameters field :template_parameters field :metadata field :_id field :access_token field :access_token_secret field :realm_id field :token_span field :authorized_at end list do field :namespace field :name field :status field :client field :updated_at end fields :namespace, :name, :status, :client, :updated_at end config.model Setup::Oauth2Authorization do weight 333 label 'OAuth 2.0 authorization' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :expires_in do pretty_value do "#{value}s" if value end end edit do field :namespace, :enum_edit field :name field :client field :scopes do visible { bindings[:object].ready_to_save? } associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end field :parameters do visible { bindings[:object].ready_to_save? } end field :template_parameters do visible { bindings[:object].ready_to_save? } end field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :refresh_token do group :credentials end configure :token_type do group :credentials end show do field :namespace field :name field :status field :client field :scopes field :parameters field :template_parameters field :metadata field :_id field :expires_in field :id_token field :token_type field :access_token field :token_span field :authorized_at field :refresh_token field :_id end fields :namespace, :name, :status, :client, :scopes, :updated_at end config.model Setup::AwsAuthorization do weight -334 object_label_method { :custom_title } configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end group :credentials do label 'Credentials' end configure :aws_access_key do group :credentials end configure :aws_secret_key do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end list do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :updated_at end fields :namespace, :name, :aws_access_key, :aws_secret_key, :seller, :merchant, :markets, :signature_method, :signature_version, :updated_at end config.model Setup::OauthAccessGrant do navigation_label 'Security' label 'Access Grants' weight 340 fields :created_at, :application_id, :scope end #Compute config.navigation 'Compute', icon: 'fa fa-cog' config.model Setup::AlgorithmParameter do visible false fields :name, :type, :many, :required, :default end config.model Setup::CallLink do visible false edit do field :name do read_only true help { nil } label 'Call name' end field :link do inline_add false inline_edit false help { nil } end end fields :name, :link end config.model Setup::Algorithm do navigation_label 'Compute' weight 400 object_label_method { :custom_title } extra_associations do association = Mongoid::Relations::Metadata.new( name: :stored_outputs, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::Algorithm.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end edit do field :namespace, :enum_edit field :name field :description field :parameters field :code, :code_mirror do help { 'Required' } end field :call_links do visible { bindings[:object].call_links.present? } end field :store_output field :output_datatype field :validate_output end show do field :namespace field :name field :description field :parameters field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end field :call_links field :_id field :stored_outputs end list do field :namespace field :name field :description field :parameters field :call_links field :updated_at end fields :namespace, :name, :description, :parameters, :call_links end config.model Setup::Translator do navigation_label 'Compute' weight 410 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :source_data_type, :target_data_type, :transformation, :target_importer, :source_exporter, :discard_chained_records ] end end edit do field :namespace, :enum_edit field :name field :type field :source_data_type do inline_edit false inline_add false visible { [:Export, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :target_data_type do inline_edit false inline_add false visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :discard_events do visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help "Events won't be fired for created or updated records if checked" end field :style do visible { bindings[:object].type.present? } help 'Required' end field :bulk_source do visible { bindings[:object].type == :Export && bindings[:object].style.present? && bindings[:object].source_bulkable? } end field :mime_type do label 'MIME type' visible { bindings[:object].type == :Export && bindings[:object].style.present? } end field :file_extension do visible { bindings[:object].type == :Export && !bindings[:object].file_extension_enum.empty? } help { "Extensions for #{bindings[:object].mime_type}" } end field :source_handler do visible { (t = bindings[:object]).style.present? && (t.type == :Update || (t.type == :Conversion && t.style == 'ruby')) } help { 'Handle sources on transformation' } end field :transformation, :code_mirror do visible { bindings[:object].style.present? && bindings[:object].style != 'chain' } help { 'Required' } html_attributes do { cols: '74', rows: '15' } end end field :source_exporter do inline_add { bindings[:object].source_exporter.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type } help 'Required' associated_collection_scope do data_type = bindings[:object].source_data_type Proc.new { |scope| scope.all(type: :Conversion, source_data_type: data_type) } end end field :target_importer do inline_add { bindings[:object].target_importer.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help 'Required' associated_collection_scope do translator = bindings[:object] source_data_type = if translator.source_exporter translator.source_exporter.target_data_type else translator.source_data_type end target_data_type = bindings[:object].target_data_type Proc.new { |scope| scope = scope.all(type: :Conversion, source_data_type: source_data_type, target_data_type: target_data_type) } end end field :discard_chained_records do visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help "Chained records won't be saved if checked" end end show do field :namespace field :name field :type field :source_data_type field :bulk_source field :target_data_type field :discard_events field :style field :mime_type field :file_extension field :transformation do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :source_exporter field :target_importer field :discard_chained_records field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :type field :style field :mime_type field :file_extension field :transformation field :updated_at end fields :namespace, :name, :type, :style, :transformation, :updated_at end config.model Setup::AlgorithmOutput do navigation_label 'Compute' weight -405 visible false configure :records_count configure :input_parameters configure :created_at do label 'Recorded at' end extra_associations do association = Mongoid::Relations::Metadata.new( name: :records, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::AlgorithmOutput.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end show do field :created_at field :input_parameters field :records_count end fields :created_at, :input_parameters, :records_count end config.model Setup::Action do visible false navigation_label 'Compute' weight -402 object_label_method { :to_s } fields :method, :path, :algorithm end config.model Setup::Application do navigation_label 'Compute' weight 420 object_label_method { :custom_title } visible configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :slug field :actions field :application_parameters end list do field :namespace field :name field :slug field :registered field :actions field :application_parameters field :updated_at end fields :namespace, :name, :slug, :identifier, :secret_token, :registered, :actions, :application_parameters end config.model Setup::ApplicationParameter do visible false navigation_label 'Compute' configure :group, :enum_edit list do field :name field :type field :many field :group field :description field :updated_at end fields :name, :type, :many, :group, :description end config.model Setup::Snippet do navigation_label 'Compute' weight 430 object_label_method { :custom_title } visible configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :type field :description field :code, :code_mirror do html_attributes do { cols: '74', rows: '15' } end help { 'Required' } config do { lineNumbers: true, mode: bindings[:object].type} end end field :tags end show do field :namespace, :enum_edit field :name field :type field :description field :code do pretty_value do "<pre><code class='#{bindings[:object].type}'>#{value}</code></pre>".html_safe end end field :tags end list do field :namespace field :name field :type field :tags end fields :namespace, :name, :type, :description, :code, :tags end #Workflows config.navigation 'Workflows', icon: 'fa fa-cogs' config.model Setup::Flow do navigation_label 'Workflows' weight 500 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :custom_data_type, :data_type_scope, :scope_filter, :scope_evaluator, :lot_size, :connection_role, :webhook, :response_translator, :response_data_type ] end end Setup::FlowConfig.config_fields.each do |f| configure f.to_sym, Setup::Flow.data_type.schema['properties'][f]['type'].to_sym end edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :event, :optional_belongs_to do inline_edit false inline_add false visible do (f = bindings[:object]).not_shared? || f.data_type_scope.present? end end field :translator do help I18n.t('admin.form.required') shared_read_only end field :custom_data_type, :optional_belongs_to do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] if (t = f.translator) && t.data_type.nil? unless f.data_type if f.custom_data_type_selected? f.custom_data_type = nil f.data_type_scope = nil else f.custom_data_type = f.event.try(:data_type) end end true else f.custom_data_type = nil false end end required do bindings[:object].event.present? end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_data_type') else I18n.t('admin.form.flow.target_data_type') end else I18n.t('admin.form.flow.data_type') end end end field :data_type_scope do shared_read_only visible do f = bindings[:object] #For filter scope bindings[:controller].instance_variable_set(:@_data_type, f.data_type) bindings[:controller].instance_variable_set(:@_update_field, 'translator_id') if f.shared? value.present? else f.event && (t = f.translator) && t.type != :Import && (f.custom_data_type_selected? || f.data_type) end end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_scope') else I18n.t('admin.form.flow.target_scope') end else I18n.t('admin.form.flow.data_type_scope') end end help I18n.t('admin.form.required') end field :scope_filter do shared_read_only visible do f = bindings[:object] f.scope_symbol == :filtered end partial 'form_triggers' help I18n.t('admin.form.required') end field :scope_evaluator do inline_add false inline_edit false shared_read_only visible do f = bindings[:object] f.scope_symbol == :evaluation end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end help I18n.t('admin.form.required') end field :lot_size do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.custom_data_type_selected? && (f.event.blank? || f.data_type.blank? || (f.data_type_scope.present? && f.scope_symbol != :event_source)) end end field :webhook do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end help I18n.t('admin.form.required') end field :authorization do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :connection_role do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :before_submit do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :response_translator do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.ready_to_save? end associated_collection_scope do Proc.new { |scope| scope.where(type: :Import) } end end field :response_data_type do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] (resp_t = f.response_translator) && resp_t.type == :Import && resp_t.data_type.nil? end help I18n.t('admin.form.required') end field :discard_events do visible do f = bindings[:object] ((f.translator && f.translator.type == :Import) || f.response_translator.present?) && f.ready_to_save? end help I18n.t('admin.form.flow.events_wont_be_fired') end field :active do visible do f = bindings[:object] f.ready_to_save? end end field :notify_request do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help I18n.t('admin.form.flow.notify_request') end field :notify_response do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help help I18n.t('admin.form.flow.notify_response') end field :after_process_callbacks do shared_read_only visible do bindings[:object].ready_to_save? end help I18n.t('admin.form.flow.after_process_callbacks') associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end end show do field :namespace field :name field :active field :event field :translator field :custom_data_type field :data_type_scope field :scope_filter field :scope_evaluator field :lot_size field :webhook field :authorization field :connection_role field :before_submit field :response_translator field :response_data_type field :discard_events field :notify_request field :notify_response field :after_process_callbacks field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :active field :event field :translator field :updated_at end fields :namespace, :name, :active, :event, :translator, :updated_at end config.model Setup::Event do navigation_label 'Workflows' weight 510 object_label_method { :custom_title } visible false configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name end show do field :namespace field :name field :_type field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Observer do navigation_label 'Workflows' weight 511 label 'Data Event' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :data_type do inline_add false inline_edit false associated_collection_scope do data_type = bindings[:object].data_type Proc.new { |scope| if data_type scope.where(id: data_type.id) else scope end } end help 'Required' end field :trigger_evaluator do visible { (obj = bindings[:object]).data_type.blank? || obj.trigger_evaluator.present? || obj.triggers.nil? } associated_collection_scope do Proc.new { |scope| scope.all.or(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :triggers do visible do bindings[:controller].instance_variable_set(:@_data_type, data_type = bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'data_type_id') data_type.present? && !bindings[:object].trigger_evaluator.present? end partial 'form_triggers' help false end end show do field :namespace field :name field :data_type field :triggers field :trigger_evaluator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :data_type, :triggers, :trigger_evaluator, :updated_at end config.model Setup::Scheduler do navigation_label 'Workflows' weight 512 object_label_method { :custom_title } configure :expression, :json_value edit do field :namespace, :enum_edit field :name field :expression do visible true label 'Scheduling type' help 'Configure scheduler' partial :scheduler html_attributes do { rows: '1' } end end end show do field :namespace field :name field :expression field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :expression field :activated field :updated_at end fields :namespace, :name, :expression, :activated, :updated_at end #Monitors config.navigation 'Monitors', icon: 'fa fa-heartbeat' config.model Setup::Notification do navigation_label 'Monitors' weight 600 object_label_method { :label } show_in_dashboard false configure :created_at configure :type do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value.to_s.capitalize}</label>".html_safe end end configure :message do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value}</label>".html_safe end end configure :attachment, :storage_file list do field :created_at do visible do if account = Account.current account.notifications_listed_at = Time.now end true end end field :type field :message field :attachment field :task field :updated_at end end config.model Setup::Task do navigation_label 'Monitors' weight 610 object_label_method { :to_s } show_in_dashboard false configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :updated_at end config.model Setup::FlowExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :flow, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeGeneration do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeExpansion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Translation do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Push do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :source_collection, :shared_collection, :description, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::BasePull do navigation_label 'Monitors' visible false label 'Pull' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::PullImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :data do label 'Pull data' end edit do field :description end fields :data, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SharedCollectionPull do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :shared_collection, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SchemasImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :base_uri, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Deletion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :deletion_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.contextualized_label(:menu), v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end edit do field :description end fields :deletion_model, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::AlgorithmExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :algorithm, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Submission do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :webhook, :connection, :authorization, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Storage do navigation_label 'Monitors' show_in_dashboard false weight 620 object_label_method { :label } configure :filename do label 'File name' pretty_value { bindings[:object].storage_name } end configure :length do label 'Size' pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_length) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.reject(&:nil?).max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end configure :storer_model, :model do label 'Model' end configure :storer_object, :record do label 'Object' end configure :storer_property do label 'Property' end list do field :storer_model field :storer_object field :storer_property field :filename field :contentType field :length field :updated_at end fields :storer_model, :storer_object, :storer_property, :filename, :contentType, :length end #Configuration config.navigation 'Configuration', icon: 'fa fa-sliders' config.model Setup::Namespace do navigation_label 'Configuration' weight 700 fields :name, :slug, :updated_at end config.model Setup::DataTypeConfig do navigation_label 'Configuration' label 'Data Type Config' weight 710 configure :data_type do read_only true end fields :data_type, :slug, :navigation_link, :updated_at end config.model Setup::FlowConfig do navigation_label 'Configuration' label 'Flow Config' weight 720 configure :flow do read_only true end fields :flow, :active, :notify_request, :notify_response, :discard_events end config.model Setup::ConnectionConfig do navigation_label 'Configuration' label 'Connection Config' weight 730 configure :connection do read_only true end configure :number do label 'Key' end fields :connection, :number, :token end config.model Setup::Pin do navigation_label 'Configuration' weight 740 object_label_method :to_s configure :model, :model configure :record, :record edit do field :record_model do label 'Model' help 'Required' end Setup::Pin.models.values.each do |m_data| field m_data[:property] do inline_add false inline_edit false help 'Required' visible { bindings[:object].record_model == m_data[:model_name] } associated_collection_scope do field = "#{m_data[:property]}_id".to_sym excluded_ids = Setup::Pin.where(field.exists => true).collect(&field) unless (pin = bindings[:object]).nil? || pin.new_record? excluded_ids.delete(pin[field]) end Proc.new { |scope| scope.where(origin: :shared, :id.nin => excluded_ids) } end end end field :version do help 'Required' visible { bindings[:object].ready_to_save? } end end show do field :model Setup::Pin.models.values.each do |m_data| field m_data[:property] end field :version field :updated_at end fields :model, :record, :version, :updated_at end config.model Setup::Binding do navigation_label 'Configuration' weight 750 configure :binder_model, :model configure :binder, :record configure :bind_model, :model configure :bind, :record fields :binder_model, :binder, :bind_model, :bind, :updated_at end config.model Setup::ParameterConfig do navigation_label 'Configuration' label 'Parameter' weight 760 configure :parent_model, :model configure :parent, :record edit do field :parent_model do read_only true help '' end field :parent do read_only true help '' end field :location do read_only true help '' end field :name do read_only true help '' end field :value end fields :parent_model, :parent, :location, :name, :value, :updated_at end #Administration config.navigation 'Administration', icon: 'fa fa-user-secret' config.model User do weight 800 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :label } group :credentials do label 'Credentials' active true end group :activity do label 'Activity' active true end configure :name configure :email configure :roles configure :account do read_only { true } end configure :password do group :credentials end configure :password_confirmation do group :credentials end configure :key do group :credentials end configure :authentication_token do group :credentials end configure :confirmed_at do group :activity end configure :sign_in_count do group :activity end configure :current_sign_in_at do group :activity end configure :last_sign_in_at do group :activity end configure :current_sign_in_ip do group :activity end configure :last_sign_in_ip do group :activity end edit do field :picture field :name field :email do visible { Account.current_super_admin? } end field :roles do visible { Account.current_super_admin? } end field :account do label { Account.current_super_admin? ? 'Account' : 'Account settings' } help { nil } end field :password do visible { Account.current_super_admin? } end field :password_confirmation do visible { Account.current_super_admin? } end field :key do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :authentication_token do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :confirmed_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :sign_in_count do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end end show do field :picture field :name field :email field :account field :roles field :key field :authentication_token field :sign_in_count field :current_sign_in_at field :last_sign_in_at field :current_sign_in_ip field :last_sign_in_ip end list do field :picture do thumb_method :icon end field :name field :email field :account field :roles field :key field :authentication_token field :sign_in_count field :created_at field :updated_at end end config.model Account do weight 810 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :label } configure :_id do visible { Account.current_super_admin? } end configure :name do visible { Account.current_super_admin? } end configure :owner do read_only { !Account.current_super_admin? } help { nil } end configure :tenant_account do visible { Account.current_super_admin? } end configure :number do visible { Account.current_super_admin? } end configure :users do visible { Account.current_super_admin? } end configure :notification_level configure :time_zone do label 'Time Zone' end fields :_id, :name, :owner, :tenant_account, :number, :users, :notification_level, :time_zone end config.model Role do weight 810 navigation_label 'Administration' visible { User.current_super_admin? } configure :users do visible { Account.current_super_admin? } end fields :name, :users end config.model Setup::SharedName do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } fields :name, :owners, :updated_at end config.model Script do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } edit do field :name field :description field :code, :code_mirror end show do field :name field :description field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end end list do field :name field :description field :code field :updated_at end fields :name, :description, :code, :updated_at end config.model CenitToken do weight 890 navigation_label 'Administration' visible { User.current_super_admin? } end config.model Setup::DelayedMessage do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model Setup::SystemNotification do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model RabbitConsumer do weight 850 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :to_s } configure :task_id do pretty_value do if (executor = (obj = bindings[:object]).executor) && (task = obj.executing_task) v = bindings[:view] amc = RailsAdmin.config(task.class) am = amc.abstract_model wording = task.send(amc.object_label_method) amc = RailsAdmin.config(Account) am = amc.abstract_model if (inspect_action = v.action(:inspect, am, executor)) task_path = v.show_path(model_name: task.class.to_s.underscore.gsub('/', '~'), id: task.id.to_s) v.link_to(wording, v.url_for(action: inspect_action.action_name, model_name: am.to_param, id: executor.id, params: { return_to: task_path })) else wording end.html_safe end end end list do field :channel field :tag field :executor field :task_id field :alive field :updated_at end fields :created_at, :channel, :tag, :executor, :task_id, :alive, :created_at, :updated_at end config.model ApplicationId do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } label 'Application ID' register_instance_option(:discard_submit_buttons) { bindings[:object].instance_variable_get(:@registering) } configure :name configure :registered, :boolean configure :redirect_uris, :json_value edit do field :oauth_name do visible { bindings[:object].instance_variable_get(:@registering) } end field :redirect_uris do visible { bindings[:object].instance_variable_get(:@registering) } end end list do field :name field :registered field :account field :identifier field :updated_at end fields :created_at, :name, :registered, :account, :identifier, :created_at, :updated_at end config.model Setup::ScriptExecution do weight 840 parent { nil } navigation_label 'Administration' object_label_method { :to_s } visible { User.current_super_admin? } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end list do field :script field :description field :scheduler field :attempts_succeded field :retries field :progress field :status field :notifications field :updated_at end fields :script, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end end fixed codemirror [ RailsAdmin::Config::Actions::DiskUsage, RailsAdmin::Config::Actions::SendToFlow, RailsAdmin::Config::Actions::SwitchNavigation, RailsAdmin::Config::Actions::DataType, RailsAdmin::Config::Actions::Import, #RailsAdmin::Config::Actions::EdiExport, RailsAdmin::Config::Actions::ImportSchema, RailsAdmin::Config::Actions::DeleteAll, RailsAdmin::Config::Actions::TranslatorUpdate, RailsAdmin::Config::Actions::Convert, RailsAdmin::Config::Actions::SimpleShare, RailsAdmin::Config::Actions::BulkShare, RailsAdmin::Config::Actions::Pull, RailsAdmin::Config::Actions::RetryTask, RailsAdmin::Config::Actions::DownloadFile, RailsAdmin::Config::Actions::ProcessFlow, RailsAdmin::Config::Actions::BuildGem, RailsAdmin::Config::Actions::Run, RailsAdmin::Config::Actions::Authorize, RailsAdmin::Config::Actions::SimpleDeleteDataType, RailsAdmin::Config::Actions::BulkDeleteDataType, RailsAdmin::Config::Actions::SimpleGenerate, RailsAdmin::Config::Actions::BulkGenerate, RailsAdmin::Config::Actions::SimpleExpand, RailsAdmin::Config::Actions::BulkExpand, RailsAdmin::Config::Actions::Records, RailsAdmin::Config::Actions::SwitchScheduler, RailsAdmin::Config::Actions::SimpleExport, RailsAdmin::Config::Actions::Schedule, RailsAdmin::Config::Actions::Submit, RailsAdmin::Config::Actions::Trash, RailsAdmin::Config::Actions::Inspect, RailsAdmin::Config::Actions::Copy, RailsAdmin::Config::Actions::Cancel, RailsAdmin::Config::Actions::Configure, RailsAdmin::Config::Actions::SimpleCrossShare, RailsAdmin::Config::Actions::BulkCrossShare, RailsAdmin::Config::Actions::Regist, RailsAdmin::Config::Actions::SharedCollectionIndex, RailsAdmin::Config::Actions::BulkPull, RailsAdmin::Config::Actions::CleanUp, RailsAdmin::Config::Actions::ShowRecords, RailsAdmin::Config::Actions::RunScript, RailsAdmin::Config::Actions::Play, RailsAdmin::Config::Actions::PullImport, RailsAdmin::Config::Actions::State, RailsAdmin::Config::Actions::Documentation, RailsAdmin::Config::Actions::Push ].each { |a| RailsAdmin::Config::Actions.register(a) } RailsAdmin::Config::Actions.register(:export, RailsAdmin::Config::Actions::BulkExport) [ RailsAdmin::Config::Fields::Types::JsonValue, RailsAdmin::Config::Fields::Types::JsonSchema, RailsAdmin::Config::Fields::Types::StorageFile, RailsAdmin::Config::Fields::Types::EnumEdit, RailsAdmin::Config::Fields::Types::Model, RailsAdmin::Config::Fields::Types::Record, RailsAdmin::Config::Fields::Types::HtmlErb, RailsAdmin::Config::Fields::Types::OptionalBelongsTo ].each { |f| RailsAdmin::Config::Fields::Types.register(f) } module RailsAdmin module Config class << self def navigation(label, options) navigation_options[label.to_s] = options end def navigation_options @nav_options ||= {} end end end end RailsAdmin.config do |config| config.total_columns_width = 900 ## == PaperTrail == # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration config.authenticate_with do warden.authenticate! scope: :user unless %w(dashboard shared_collection_index index show).include?(action_name) end config.current_user_method { current_user } config.audit_with :mongoid_audit config.authorize_with :cancan config.excluded_models += [Setup::BaseOauthAuthorization, Setup::AwsAuthorization] config.actions do dashboard # mandatory # disk_usage shared_collection_index index # mandatory new { except [Setup::Event, Setup::DataType, Setup::Authorization, Setup::BaseOauthProvider] } import import_schema pull_import translator_update convert export bulk_delete show show_records run run_script edit configure play copy simple_share bulk_share simple_cross_share bulk_cross_share build_gem pull bulk_pull push download_file process_flow authorize simple_generate bulk_generate simple_expand bulk_expand records switch_navigation switch_scheduler simple_export schedule state retry_task submit inspect cancel regist simple_delete_data_type bulk_delete_data_type delete trash clean_up #show_in_app send_to_flow delete_all data_type #history_index history_show do only do [ Setup::Algorithm, Setup::Connection, Setup::Webhook, Setup::Translator, Setup::Flow, Setup::OauthClient, Setup::Oauth2Scope ] + Setup::DataType.class_hierarchy + Setup::Validator.class_hierarchy + Setup::BaseOauthProvider.class_hierarchy end visible { only.include?((obj = bindings[:object]).class) && obj.try(:shared?) } end documentation end def shared_read_only instance_eval do read_only { (obj = bindings[:object]).creator_id != User.current.id && obj.shared? } end end shared_non_editable = Proc.new do shared_read_only end #Collections config.navigation 'Collections', icon: 'fa fa-cubes' config.model Setup::CrossCollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CrossCollectionPullParameter do visible false object_label_method { :label } configure :location, :json_value edit do field :label field :property_name field :location end show do field :label field :property_name field :location field :created_at #field :creator field :updated_at end fields :label, :property_name, :location end config.model Setup::CrossSharedCollection do weight 000 label 'Cross Shared Collection' navigation_label 'Collections' object_label_method :versioned_name visible { Account.current_super_admin? } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' configure :readme, :html_erb configure :pull_data, :json_value configure :data, :json_value configure :swagger_spec, :json_value group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :image field :logo_background, :color field :name field :shared_version field :summary field :category field :authors field :pull_count field :pull_parameters field :dependencies field :readme end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary field :readme field :authors field :pull_count field :_id field :updated_at field :data_schemas do label 'Schemas' group :data end field :data_custom_validators do label 'Validators' group :data end field :data_data_types do label 'Data Types' group :data end field :data_connections do label 'Connections' group :api_connectors end field :data_webhooks do label 'Webhooks' group :api_connectors end field :data_connection_roles do label 'Connection Roles' group :api_connectors end field :data_flows do label 'Flows' group :workflows end field :data_events do label 'Events' group :workflows end field :data_translators do label 'Translators' group :workflows end field :data_algorithms do label 'Algorithms' group :workflows end field :data_applications do label 'Applications' group :workflows end field :data_authorizations do label 'Autorizations' group :security end field :data_oauth_clients do label 'OAuth Clients' group :security end field :data_oauth_providers do label 'OAuth Providers' group :security end field :data_oauth2_scopes do label 'OAuth 2.0 Scopes' group :security end field :data_namespaces do label 'Namespaces' group :config end end end config.model Setup::SharedCollection do weight 010 label 'Shared Collection' register_instance_option(:discard_submit_buttons) do !(a = bindings[:action]) || a.key != :edit end navigation_label 'Collections' object_label_method { :versioned_name } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' group :collections group :workflows group :api_connectors do label 'Connectors' active true end group :data group :security edit do field :image do visible { !bindings[:object].instance_variable_get(:@sharing) } end field :logo_background field :name do required { true } end field :shared_version do required { true } end field :authors field :summary field :source_collection do visible { !((source_collection = bindings[:object].source_collection) && source_collection.new_record?) } inline_edit false inline_add false associated_collection_scope do source_collection = (obj = bindings[:object]).source_collection Proc.new { |scope| if obj.new_record? scope.where(id: source_collection ? source_collection.id : nil) else scope end } end end field :connections do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_connections)).nil? || v) end help do nil end pretty_value do if bindings[:object].connections.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[connection_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No connection selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && obj.source_collection && obj.source_collection.connections.present? end associated_collection_scope do source_collection = bindings[:object].source_collection connections = (source_collection && source_collection.connections) || [] Proc.new { |scope| scope.any_in(id: connections.collect { |connection| connection.id }) } end end field :dependencies do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_dependencies)).nil? || v) end help do nil end pretty_value do if bindings[:object].dependencies.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[dependency_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No dependencies selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) end end field :pull_parameters field :pull_count do visible { Account.current_super_admin? } end field :readme do visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && !obj.instance_variable_get(:@_selecting_connections) end end end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary do pretty_value do value.html_safe end end field :readme, :html_erb field :authors field :dependencies field :pull_count field :data_namespaces do group :collections label 'Namespaces' list_fields do %w(name slug) end end field :data_flows do group :workflows label 'Flows' list_fields do %w(namespace name) #TODO Inlude a description field on Flow model end end field :data_translators do group :workflows label 'Translators' list_fields do %w(namespace name type style) end end field :data_events do group :workflows label 'Events' list_fields do %w(namespace name _type) end end field :data_algorithms do group :workflows label 'Algorithms' list_fields do %w(namespace name description) end end field :data_connection_roles do group :api_connectors label 'Connection roles' list_fields do %w(namespace name) end end field :data_webhooks do group :api_connectors label 'Webhooks' list_fields do %w(namespace name path method description) end end field :data_connections do group :api_connectors label 'Connections' list_fields do %w(namespace name url) end end field :data_data_types do group :data label 'Data types' list_fields do %w(title name slug _type) end end field :data_schemas do group :data label 'Schemas' list_fields do %w(namespace uri) end end field :data_custom_validators do group :data label 'Custom validators' list_fields do %w(namespace name _type) #TODO Include a description field for Custom Validator model end end # field :data_data TODO Include collection data field field :data_authorizations do group :security label 'Authorizations' list_fields do %w(namespace name _type) end end field :data_oauth_providers do group :security label 'OAuth providers' list_fields do %w(namespace name response_type authorization_endpoint token_endpoint token_method _type) end end field :data_oauth_clients do group :security label 'OAuth clients' list_fields do %w(provider name) end end field :data_oauth2_scopes do group :security label 'OAuth 2.0 scopes' list_fields do %w(provider name description) end end field :_id field :updated_at end list do field :image do thumb_method :icon end field :name do pretty_value do bindings[:object].versioned_name end end field :authors field :summary field :pull_count field :dependencies end end config.model Setup::CollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CollectionPullParameter do visible false object_label_method { :label } field :label field :parameter, :enum do enum do bindings[:controller].instance_variable_get(:@shared_parameter_enum) || [bindings[:object].parameter] end end edit do field :label field :parameter field :property_name field :location, :json_value end show do field :label field :parameter field :created_at #field :creator field :updated_at end list do field :label field :parameter field :updated_at end fields :label, :parameter end config.model Setup::CollectionData do visible false object_label_method { :label } end config.model Setup::Collection do weight 020 navigation_label 'Collections' register_instance_option :label_navigation do 'My Collections' end group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :image field :readme do visible { Account.current_super_admin? } end field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data end show do field :image field :readme, :html_erb field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data field :namespaces field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :image do thumb_method :icon end field :name field :flows do pretty_value do value.count > 0 ? value.count : '-' end end field :connection_roles do pretty_value do value.count > 0 ? value.count : '-' end end field :translators do pretty_value do value.count > 0 ? value.count : '-' end end field :events do pretty_value do value.count > 0 ? value.count : '-' end end field :data_types do pretty_value do value.count > 0 ? value.count : '-' end end field :schemas do pretty_value do value.count > 0 ? value.count : '-' end end field :custom_validators do pretty_value do value.count > 0 ? value.count : '-' end end field :algorithms do pretty_value do value.count > 0 ? value.count : '-' end end field :applications do pretty_value do value.count > 0 ? value.count : '-' end end field :webhooks do pretty_value do value.count > 0 ? value.count : '-' end end field :connections do pretty_value do value.count > 0 ? value.count : '-' end end field :authorizations do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_providers do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_clients do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth2_scopes do pretty_value do value.count > 0 ? value.count : '-' end end field :data field :updated_at end end #Definitions config.navigation 'Definitions', icon: 'fa fa-puzzle-piece' config.model Setup::Validator do navigation_label 'Definitions' label 'Validators' weight 100 fields :namespace, :name fields :namespace, :name, :updated_at show_in_dashboard false end config.model Setup::CustomValidator do visible false configure :_type do pretty_value do value.split('::').last.to_title end end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Schema do weight 101 object_label_method { :custom_title } edit do field :namespace, :enum_edit do read_only { !bindings[:object].new_record? } end field :uri do read_only { !bindings[:object].new_record? } html_attributes do { cols: '74', rows: '1' } end end field :schema, :code_mirror do html_attributes do { cols: '74', rows: '15' } end config do { lineNumbers: true } end end field :schema_data_type do inline_edit false inline_add false end end show do field :namespace field :uri field :schema do pretty_value do v = if json = JSON.parse(value) rescue nil "<code class='json'>#{JSON.pretty_generate(json).gsub('<', '&lt;').gsub('>', '&gt;')}</code>" elsif (xml = Nokogiri::XML(value)).errors.blank? "<code class='xml'>#{xml.to_xml.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else "<code>#{value}</code>" end "<pre>#{v}</pre>".html_safe end end field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :uri, :schema_data_type, :updated_at end config.model Setup::XsltValidator do parent Setup::Validator weight 102 label 'XSLT Validator' object_label_method { :custom_title } list do field :namespace field :xslt field :updated_at end fields :namespace, :name, :xslt, :updated_at end config.model Setup::EdiValidator do parent Setup::Validator weight 103 object_label_method { :custom_title } label 'EDI Validator' edit do field :namespace, :enum_edit field :name field :schema_data_type field :content_type end fields :namespace, :name, :schema_data_type, :content_type, :updated_at end config.model Setup::AlgorithmValidator do parent Setup::Validator weight 104 label 'Algorithm Validator' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :algorithm end fields :namespace, :name, :algorithm, :updated_at end config.model Setup::DataType do navigation_label 'Definitions' weight 110 label 'Data Type' object_label_method { :custom_title } visible true show_in_dashboard false configure :_type do pretty_value do value.split('::').last.to_title end end group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :slug configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :title, :enum_edit, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::DataType.fields[:used_memory.to_s].type.new(Setup::DataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::DataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :name field :title field :slug field :_type field :storage_size field :schema do pretty_value do v = if json = JSON.pretty_generate(value) rescue nil "<code class='json'>#{json.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else value end "<pre>#{v}</pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :_type, :storage_size, :updated_at end config.model Setup::JsonDataType do navigation_label 'Definitions' weight 111 label 'JSON Data Type' object_label_method { :custom_title } group :behavior do label 'Behavior' active false end configure :title configure :name do read_only { !bindings[:object].new_record? } end configure :schema, :code_mirror do html_attributes do { cols: '74', rows: '15' } end # pretty_value do # "<pre><code class='json'>#{JSON.pretty_generate(value)}</code></pre>".html_safe # end end configure :storage_size, :decimal do pretty_value do if (objects = bindings[:controller].instance_variable_get(:@objects)) unless (max = bindings[:controller].instance_variable_get(:@max_storage_size)) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :schema, :json_schema do shared_read_only help { 'Required' } end field :title, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless (max = bindings[:controller].instance_variable_get(:@max_used_memory)) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :title field :name field :slug field :storage_size field :schema do pretty_value do "<pre><code class='ruby'>#{JSON.pretty_generate(value)}</code></pre>".html_safe end end field :before_save_callbacks field :records_methods field :data_type_methods field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end config.model Setup::FileDataType do navigation_label 'Definitions' weight 112 label 'File Data Type' object_label_method { :custom_title } group :content do label 'Content' end group :behavior do label 'Behavior' active false end configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :validators do group :content inline_add false end configure :schema_data_type do group :content inline_add false inline_edit false end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :title, &shared_non_editable field :slug field :validators, &shared_non_editable field :schema_data_type, &shared_non_editable field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :validators field :schema_data_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :title field :name field :slug field :validators field :storage_size field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end #Connectors config.navigation 'Connectors', icon: 'fa fa-plug' config.model Setup::Parameter do visible false object_label_method { :to_s } configure :metadata, :json_value configure :value edit do field :name field :value field :description field :metadata end list do field :name field :value field :description field :metadata field :updated_at end end config.model Setup::Connection do navigation_label 'Connectors' weight 200 object_label_method { :custom_title } group :credentials do label 'Credentials' end configure :number, :string do label 'Key' html_attributes do { maxlength: 30, size: 30 } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :token, :text do html_attributes do { cols: '50', rows: '1' } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:url, &shared_non_editable) field :number field :token field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :url field :number field :token field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at field :updated_at end list do field :namespace field :name field :url field :number field :token field :authorization field :updated_at end fields :namespace, :name, :url, :number, :token, :authorization, :updated_at end config.model Setup::ConnectionRole do navigation_label 'Connectors' weight 210 label 'Connection Role' object_label_method { :custom_title } configure :name, :string do help 'Requiered.' html_attributes do { maxlength: 50, size: 50 } end end configure :webhooks do nested_form false end configure :connections do nested_form false end modal do field :namespace, :enum_edit field :name field :webhooks field :connections end show do field :namespace field :name field :webhooks field :connections field :_id field :created_at #field :creator field :updated_at #field :updater end edit do field :namespace, :enum_edit field :name field :webhooks field :connections end fields :namespace, :name, :webhooks, :connections, :updated_at end config.model Setup::Webhook do navigation_label 'Connectors' weight 220 object_label_method { :custom_title } configure :metadata, :json_value group :credentials do label 'Credentials' end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :path, :string do help 'Requiered. Path of the webhook relative to connection URL.' html_attributes do { maxlength: 255, size: 100 } end end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:path, &shared_non_editable) field(:method, &shared_non_editable) field(:description, &shared_non_editable) field(:metadata, :json_value, &shared_non_editable) field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :path field :method field :description field :metadata, :json_value field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :path, :method, :description, :authorization, :updated_at end #Security config.navigation 'Security', icon: 'fa fa-shield' config.model Setup::OauthClient do navigation_label 'Security' label 'OAuth Client' weight 300 object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :identifier do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :secret do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end fields :provider, :name, :identifier, :secret, :tenant, :updated_at end config.model Setup::BaseOauthProvider do navigation_label 'Security' weight 310 object_label_method { :custom_title } label 'Provider' configure :_type do pretty_value do value.split('::').last.to_title end end configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :namespace, :enum_edit list do field :namespace field :name field :_type field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :tenant field :updated_at end fields :namespace, :name, :_type, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :tenant end config.model Setup::OauthProvider do weight 311 label 'OAuth 1.0 provider' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit, &shared_non_editable field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :request_token_endpoint field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :request_token_endpoint, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Provider do weight 312 label 'OAuth 2.0 provider' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :scope_separator field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :scope_separator, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Scope do navigation_label 'Security' weight 320 label 'OAuth 2.0 Scope' object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end fields :provider, :name, :description, :tenant, :updated_at end config.model Setup::Authorization do navigation_label 'Security' weight 330 object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name field :metadata end fields :namespace, :name, :status, :_type, :metadata, :updated_at show_in_dashboard false end config.model Setup::BasicAuthorization do weight 331 register_instance_option :label_navigation do 'Basic' end object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value edit do field :namespace field :name field :username field :password field :metadata end group :credentials do label 'Credentials' end configure :username do group :credentials end configure :password do group :credentials end show do field :namespace field :name field :status field :username field :password field :metadata field :_id end edit do field :namespace, :enum_edit field :name field :username field :password end fields :namespace, :name, :status, :username, :password, :updated_at end config.model Setup::OauthAuthorization do weight 332 label 'OAuth 1.0 authorization' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace, :enum_edit field :name field :client field :parameters field :template_parameters field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :access_token_secret do group :credentials end configure :realm_id do group :credentials end show do field :namespace field :name field :status field :client field :parameters field :template_parameters field :metadata field :_id field :access_token field :access_token_secret field :realm_id field :token_span field :authorized_at end list do field :namespace field :name field :status field :client field :updated_at end fields :namespace, :name, :status, :client, :updated_at end config.model Setup::Oauth2Authorization do weight 333 label 'OAuth 2.0 authorization' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :expires_in do pretty_value do "#{value}s" if value end end edit do field :namespace, :enum_edit field :name field :client field :scopes do visible { bindings[:object].ready_to_save? } associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end field :parameters do visible { bindings[:object].ready_to_save? } end field :template_parameters do visible { bindings[:object].ready_to_save? } end field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :refresh_token do group :credentials end configure :token_type do group :credentials end show do field :namespace field :name field :status field :client field :scopes field :parameters field :template_parameters field :metadata field :_id field :expires_in field :id_token field :token_type field :access_token field :token_span field :authorized_at field :refresh_token field :_id end fields :namespace, :name, :status, :client, :scopes, :updated_at end config.model Setup::AwsAuthorization do weight -334 object_label_method { :custom_title } configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end group :credentials do label 'Credentials' end configure :aws_access_key do group :credentials end configure :aws_secret_key do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end list do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :updated_at end fields :namespace, :name, :aws_access_key, :aws_secret_key, :seller, :merchant, :markets, :signature_method, :signature_version, :updated_at end config.model Setup::OauthAccessGrant do navigation_label 'Security' label 'Access Grants' weight 340 fields :created_at, :application_id, :scope end #Compute config.navigation 'Compute', icon: 'fa fa-cog' config.model Setup::AlgorithmParameter do visible false fields :name, :type, :many, :required, :default end config.model Setup::CallLink do visible false edit do field :name do read_only true help { nil } label 'Call name' end field :link do inline_add false inline_edit false help { nil } end end fields :name, :link end config.model Setup::Algorithm do navigation_label 'Compute' weight 400 object_label_method { :custom_title } extra_associations do association = Mongoid::Relations::Metadata.new( name: :stored_outputs, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::Algorithm.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end edit do field :namespace, :enum_edit field :name field :description field :parameters field :code, :code_mirror do html_attributes do { cols: '74', rows: '15' } end config do { lineNumbers: true } end help { 'Required' } end field :call_links do visible { bindings[:object].call_links.present? } end field :store_output field :output_datatype field :validate_output end show do field :namespace field :name field :description field :parameters field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end field :call_links field :_id field :stored_outputs end list do field :namespace field :name field :description field :parameters field :call_links field :updated_at end fields :namespace, :name, :description, :parameters, :call_links end config.model Setup::Translator do navigation_label 'Compute' weight 410 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :source_data_type, :target_data_type, :transformation, :target_importer, :source_exporter, :discard_chained_records ] end end edit do field :namespace, :enum_edit field :name field :type field :source_data_type do inline_edit false inline_add false visible { [:Export, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :target_data_type do inline_edit false inline_add false visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :discard_events do visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help "Events won't be fired for created or updated records if checked" end field :style do visible { bindings[:object].type.present? } help 'Required' end field :bulk_source do visible { bindings[:object].type == :Export && bindings[:object].style.present? && bindings[:object].source_bulkable? } end field :mime_type do label 'MIME type' visible { bindings[:object].type == :Export && bindings[:object].style.present? } end field :file_extension do visible { bindings[:object].type == :Export && !bindings[:object].file_extension_enum.empty? } help { "Extensions for #{bindings[:object].mime_type}" } end field :source_handler do visible { (t = bindings[:object]).style.present? && (t.type == :Update || (t.type == :Conversion && t.style == 'ruby')) } help { 'Handle sources on transformation' } end field :transformation, :code_mirror do visible { bindings[:object].style.present? && bindings[:object].style != 'chain' } help { 'Required' } html_attributes do { cols: '74', rows: '15' } end config do { lineNumbers: true } end end field :source_exporter do inline_add { bindings[:object].source_exporter.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type } help 'Required' associated_collection_scope do data_type = bindings[:object].source_data_type Proc.new { |scope| scope.all(type: :Conversion, source_data_type: data_type) } end end field :target_importer do inline_add { bindings[:object].target_importer.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help 'Required' associated_collection_scope do translator = bindings[:object] source_data_type = if translator.source_exporter translator.source_exporter.target_data_type else translator.source_data_type end target_data_type = bindings[:object].target_data_type Proc.new { |scope| scope = scope.all(type: :Conversion, source_data_type: source_data_type, target_data_type: target_data_type) } end end field :discard_chained_records do visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help "Chained records won't be saved if checked" end end show do field :namespace field :name field :type field :source_data_type field :bulk_source field :target_data_type field :discard_events field :style field :mime_type field :file_extension field :transformation do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :source_exporter field :target_importer field :discard_chained_records field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :type field :style field :mime_type field :file_extension field :transformation field :updated_at end fields :namespace, :name, :type, :style, :transformation, :updated_at end config.model Setup::AlgorithmOutput do navigation_label 'Compute' weight -405 visible false configure :records_count configure :input_parameters configure :created_at do label 'Recorded at' end extra_associations do association = Mongoid::Relations::Metadata.new( name: :records, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::AlgorithmOutput.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end show do field :created_at field :input_parameters field :records_count end fields :created_at, :input_parameters, :records_count end config.model Setup::Action do visible false navigation_label 'Compute' weight -402 object_label_method { :to_s } fields :method, :path, :algorithm end config.model Setup::Application do navigation_label 'Compute' weight 420 object_label_method { :custom_title } visible configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :slug field :actions field :application_parameters end list do field :namespace field :name field :slug field :registered field :actions field :application_parameters field :updated_at end fields :namespace, :name, :slug, :identifier, :secret_token, :registered, :actions, :application_parameters end config.model Setup::ApplicationParameter do visible false navigation_label 'Compute' configure :group, :enum_edit list do field :name field :type field :many field :group field :description field :updated_at end fields :name, :type, :many, :group, :description end config.model Setup::Snippet do navigation_label 'Compute' weight 430 object_label_method { :custom_title } visible configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :type field :description field :code, :code_mirror do html_attributes do { cols: '74', rows: '15' } end help { 'Required' } config do { lineNumbers: true } end end field :tags end show do field :namespace, :enum_edit field :name field :type field :description field :code do pretty_value do "<pre><code class='#{bindings[:object].type}'>#{value}</code></pre>".html_safe end end field :tags end list do field :namespace field :name field :type field :tags end fields :namespace, :name, :type, :description, :code, :tags end #Workflows config.navigation 'Workflows', icon: 'fa fa-cogs' config.model Setup::Flow do navigation_label 'Workflows' weight 500 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :custom_data_type, :data_type_scope, :scope_filter, :scope_evaluator, :lot_size, :connection_role, :webhook, :response_translator, :response_data_type ] end end Setup::FlowConfig.config_fields.each do |f| configure f.to_sym, Setup::Flow.data_type.schema['properties'][f]['type'].to_sym end edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :event, :optional_belongs_to do inline_edit false inline_add false visible do (f = bindings[:object]).not_shared? || f.data_type_scope.present? end end field :translator do help I18n.t('admin.form.required') shared_read_only end field :custom_data_type, :optional_belongs_to do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] if (t = f.translator) && t.data_type.nil? unless f.data_type if f.custom_data_type_selected? f.custom_data_type = nil f.data_type_scope = nil else f.custom_data_type = f.event.try(:data_type) end end true else f.custom_data_type = nil false end end required do bindings[:object].event.present? end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_data_type') else I18n.t('admin.form.flow.target_data_type') end else I18n.t('admin.form.flow.data_type') end end end field :data_type_scope do shared_read_only visible do f = bindings[:object] #For filter scope bindings[:controller].instance_variable_set(:@_data_type, f.data_type) bindings[:controller].instance_variable_set(:@_update_field, 'translator_id') if f.shared? value.present? else f.event && (t = f.translator) && t.type != :Import && (f.custom_data_type_selected? || f.data_type) end end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_scope') else I18n.t('admin.form.flow.target_scope') end else I18n.t('admin.form.flow.data_type_scope') end end help I18n.t('admin.form.required') end field :scope_filter do shared_read_only visible do f = bindings[:object] f.scope_symbol == :filtered end partial 'form_triggers' help I18n.t('admin.form.required') end field :scope_evaluator do inline_add false inline_edit false shared_read_only visible do f = bindings[:object] f.scope_symbol == :evaluation end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end help I18n.t('admin.form.required') end field :lot_size do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.custom_data_type_selected? && (f.event.blank? || f.data_type.blank? || (f.data_type_scope.present? && f.scope_symbol != :event_source)) end end field :webhook do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end help I18n.t('admin.form.required') end field :authorization do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :connection_role do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :before_submit do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :response_translator do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.ready_to_save? end associated_collection_scope do Proc.new { |scope| scope.where(type: :Import) } end end field :response_data_type do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] (resp_t = f.response_translator) && resp_t.type == :Import && resp_t.data_type.nil? end help I18n.t('admin.form.required') end field :discard_events do visible do f = bindings[:object] ((f.translator && f.translator.type == :Import) || f.response_translator.present?) && f.ready_to_save? end help I18n.t('admin.form.flow.events_wont_be_fired') end field :active do visible do f = bindings[:object] f.ready_to_save? end end field :notify_request do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help I18n.t('admin.form.flow.notify_request') end field :notify_response do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help help I18n.t('admin.form.flow.notify_response') end field :after_process_callbacks do shared_read_only visible do bindings[:object].ready_to_save? end help I18n.t('admin.form.flow.after_process_callbacks') associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end end show do field :namespace field :name field :active field :event field :translator field :custom_data_type field :data_type_scope field :scope_filter field :scope_evaluator field :lot_size field :webhook field :authorization field :connection_role field :before_submit field :response_translator field :response_data_type field :discard_events field :notify_request field :notify_response field :after_process_callbacks field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :active field :event field :translator field :updated_at end fields :namespace, :name, :active, :event, :translator, :updated_at end config.model Setup::Event do navigation_label 'Workflows' weight 510 object_label_method { :custom_title } visible false configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name end show do field :namespace field :name field :_type field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Observer do navigation_label 'Workflows' weight 511 label 'Data Event' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :data_type do inline_add false inline_edit false associated_collection_scope do data_type = bindings[:object].data_type Proc.new { |scope| if data_type scope.where(id: data_type.id) else scope end } end help 'Required' end field :trigger_evaluator do visible { (obj = bindings[:object]).data_type.blank? || obj.trigger_evaluator.present? || obj.triggers.nil? } associated_collection_scope do Proc.new { |scope| scope.all.or(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :triggers do visible do bindings[:controller].instance_variable_set(:@_data_type, data_type = bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'data_type_id') data_type.present? && !bindings[:object].trigger_evaluator.present? end partial 'form_triggers' help false end end show do field :namespace field :name field :data_type field :triggers field :trigger_evaluator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :data_type, :triggers, :trigger_evaluator, :updated_at end config.model Setup::Scheduler do navigation_label 'Workflows' weight 512 object_label_method { :custom_title } configure :expression, :json_value edit do field :namespace, :enum_edit field :name field :expression do visible true label 'Scheduling type' help 'Configure scheduler' partial :scheduler html_attributes do { rows: '1' } end end end show do field :namespace field :name field :expression field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :expression field :activated field :updated_at end fields :namespace, :name, :expression, :activated, :updated_at end #Monitors config.navigation 'Monitors', icon: 'fa fa-heartbeat' config.model Setup::Notification do navigation_label 'Monitors' weight 600 object_label_method { :label } show_in_dashboard false configure :created_at configure :type do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value.to_s.capitalize}</label>".html_safe end end configure :message do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value}</label>".html_safe end end configure :attachment, :storage_file list do field :created_at do visible do if account = Account.current account.notifications_listed_at = Time.now end true end end field :type field :message field :attachment field :task field :updated_at end end config.model Setup::Task do navigation_label 'Monitors' weight 610 object_label_method { :to_s } show_in_dashboard false configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :updated_at end config.model Setup::FlowExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :flow, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeGeneration do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeExpansion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Translation do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Push do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :source_collection, :shared_collection, :description, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::BasePull do navigation_label 'Monitors' visible false label 'Pull' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::PullImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :data do label 'Pull data' end edit do field :description end fields :data, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SharedCollectionPull do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :shared_collection, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SchemasImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :base_uri, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Deletion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :deletion_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.contextualized_label(:menu), v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end edit do field :description end fields :deletion_model, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::AlgorithmExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :algorithm, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Submission do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :webhook, :connection, :authorization, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Storage do navigation_label 'Monitors' show_in_dashboard false weight 620 object_label_method { :label } configure :filename do label 'File name' pretty_value { bindings[:object].storage_name } end configure :length do label 'Size' pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_length) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.reject(&:nil?).max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end configure :storer_model, :model do label 'Model' end configure :storer_object, :record do label 'Object' end configure :storer_property do label 'Property' end list do field :storer_model field :storer_object field :storer_property field :filename field :contentType field :length field :updated_at end fields :storer_model, :storer_object, :storer_property, :filename, :contentType, :length end #Configuration config.navigation 'Configuration', icon: 'fa fa-sliders' config.model Setup::Namespace do navigation_label 'Configuration' weight 700 fields :name, :slug, :updated_at end config.model Setup::DataTypeConfig do navigation_label 'Configuration' label 'Data Type Config' weight 710 configure :data_type do read_only true end fields :data_type, :slug, :navigation_link, :updated_at end config.model Setup::FlowConfig do navigation_label 'Configuration' label 'Flow Config' weight 720 configure :flow do read_only true end fields :flow, :active, :notify_request, :notify_response, :discard_events end config.model Setup::ConnectionConfig do navigation_label 'Configuration' label 'Connection Config' weight 730 configure :connection do read_only true end configure :number do label 'Key' end fields :connection, :number, :token end config.model Setup::Pin do navigation_label 'Configuration' weight 740 object_label_method :to_s configure :model, :model configure :record, :record edit do field :record_model do label 'Model' help 'Required' end Setup::Pin.models.values.each do |m_data| field m_data[:property] do inline_add false inline_edit false help 'Required' visible { bindings[:object].record_model == m_data[:model_name] } associated_collection_scope do field = "#{m_data[:property]}_id".to_sym excluded_ids = Setup::Pin.where(field.exists => true).collect(&field) unless (pin = bindings[:object]).nil? || pin.new_record? excluded_ids.delete(pin[field]) end Proc.new { |scope| scope.where(origin: :shared, :id.nin => excluded_ids) } end end end field :version do help 'Required' visible { bindings[:object].ready_to_save? } end end show do field :model Setup::Pin.models.values.each do |m_data| field m_data[:property] end field :version field :updated_at end fields :model, :record, :version, :updated_at end config.model Setup::Binding do navigation_label 'Configuration' weight 750 configure :binder_model, :model configure :binder, :record configure :bind_model, :model configure :bind, :record fields :binder_model, :binder, :bind_model, :bind, :updated_at end config.model Setup::ParameterConfig do navigation_label 'Configuration' label 'Parameter' weight 760 configure :parent_model, :model configure :parent, :record edit do field :parent_model do read_only true help '' end field :parent do read_only true help '' end field :location do read_only true help '' end field :name do read_only true help '' end field :value end fields :parent_model, :parent, :location, :name, :value, :updated_at end #Administration config.navigation 'Administration', icon: 'fa fa-user-secret' config.model User do weight 800 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :label } group :credentials do label 'Credentials' active true end group :activity do label 'Activity' active true end configure :name configure :email configure :roles configure :account do read_only { true } end configure :password do group :credentials end configure :password_confirmation do group :credentials end configure :key do group :credentials end configure :authentication_token do group :credentials end configure :confirmed_at do group :activity end configure :sign_in_count do group :activity end configure :current_sign_in_at do group :activity end configure :last_sign_in_at do group :activity end configure :current_sign_in_ip do group :activity end configure :last_sign_in_ip do group :activity end edit do field :picture field :name field :email do visible { Account.current_super_admin? } end field :roles do visible { Account.current_super_admin? } end field :account do label { Account.current_super_admin? ? 'Account' : 'Account settings' } help { nil } end field :password do visible { Account.current_super_admin? } end field :password_confirmation do visible { Account.current_super_admin? } end field :key do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :authentication_token do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :confirmed_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :sign_in_count do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end end show do field :picture field :name field :email field :account field :roles field :key field :authentication_token field :sign_in_count field :current_sign_in_at field :last_sign_in_at field :current_sign_in_ip field :last_sign_in_ip end list do field :picture do thumb_method :icon end field :name field :email field :account field :roles field :key field :authentication_token field :sign_in_count field :created_at field :updated_at end end config.model Account do weight 810 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :label } configure :_id do visible { Account.current_super_admin? } end configure :name do visible { Account.current_super_admin? } end configure :owner do read_only { !Account.current_super_admin? } help { nil } end configure :tenant_account do visible { Account.current_super_admin? } end configure :number do visible { Account.current_super_admin? } end configure :users do visible { Account.current_super_admin? } end configure :notification_level configure :time_zone do label 'Time Zone' end fields :_id, :name, :owner, :tenant_account, :number, :users, :notification_level, :time_zone end config.model Role do weight 810 navigation_label 'Administration' visible { User.current_super_admin? } configure :users do visible { Account.current_super_admin? } end fields :name, :users end config.model Setup::SharedName do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } fields :name, :owners, :updated_at end config.model Script do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } edit do field :name field :description field :code, :code_mirror do html_attributes do { cols: '74', rows: '15' } end config do { lineNumbers: true } end end end show do field :name field :description field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end end list do field :name field :description field :code field :updated_at end fields :name, :description, :code, :updated_at end config.model CenitToken do weight 890 navigation_label 'Administration' visible { User.current_super_admin? } end config.model Setup::DelayedMessage do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model Setup::SystemNotification do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model RabbitConsumer do weight 850 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :to_s } configure :task_id do pretty_value do if (executor = (obj = bindings[:object]).executor) && (task = obj.executing_task) v = bindings[:view] amc = RailsAdmin.config(task.class) am = amc.abstract_model wording = task.send(amc.object_label_method) amc = RailsAdmin.config(Account) am = amc.abstract_model if (inspect_action = v.action(:inspect, am, executor)) task_path = v.show_path(model_name: task.class.to_s.underscore.gsub('/', '~'), id: task.id.to_s) v.link_to(wording, v.url_for(action: inspect_action.action_name, model_name: am.to_param, id: executor.id, params: { return_to: task_path })) else wording end.html_safe end end end list do field :channel field :tag field :executor field :task_id field :alive field :updated_at end fields :created_at, :channel, :tag, :executor, :task_id, :alive, :created_at, :updated_at end config.model ApplicationId do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } label 'Application ID' register_instance_option(:discard_submit_buttons) { bindings[:object].instance_variable_get(:@registering) } configure :name configure :registered, :boolean configure :redirect_uris, :json_value edit do field :oauth_name do visible { bindings[:object].instance_variable_get(:@registering) } end field :redirect_uris do visible { bindings[:object].instance_variable_get(:@registering) } end end list do field :name field :registered field :account field :identifier field :updated_at end fields :created_at, :name, :registered, :account, :identifier, :created_at, :updated_at end config.model Setup::ScriptExecution do weight 840 parent { nil } navigation_label 'Administration' object_label_method { :to_s } visible { User.current_super_admin? } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end list do field :script field :description field :scheduler field :attempts_succeded field :retries field :progress field :status field :notifications field :updated_at end fields :script, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end end
# ooooooooo. o8o oooo .o. .o8 o8o # `888 `Y88. `"' `888 .888. "888 `"' # 888 .d88' .oooo. oooo 888 .oooo.o .8"888. .oooo888 ooo. .oo. .oo. oooo ooo. .oo. # 888ooo88P' `P )88b `888 888 d88( "8 .8' `888. d88' `888 `888P"Y88bP"Y88b `888 `888P"Y88b # 888`88b. .oP"888 888 888 `"Y88b. .88ooo8888. 888 888 888 888 888 888 888 888 # 888 `88b. d8( 888 888 888 o. )88b .8' `888. 888 888 888 888 888 888 888 888 # o888o o888o `Y888""8o o888o o888o 8""888P' o88o o8888o `Y8bod88P" o888o o888o o888o o888o o888o o888o # RailsAdmin config file. Generated on October 06, 2011 19:07 # See github.com/sferik/rails_admin for more informations RailsAdmin.config do |config| config.current_user_method { current_user } # auto-generated config.main_app_name { ['SCV Sheriff', 'Admin'] } # auto-generated # ==> Authentication (before_filter) # This is run inside the controller instance so you can setup any authentication you need to. # By default, the authentication will run via warden if available. # and will run on the default user scope. # If you use devise, this will authenticate the same as authenticate_user! # Example Devise admin # RailsAdmin.config do |config| config.authenticate_with do authenticate_user! redirect_to root_path unless current_user.admin? end # end # Example Custom Warden # RailsAdmin.config do |config| # config.authenticate_with do # warden.authenticate! :scope => :paranoid # end # end # ==> Authorization # Use cancan https://github.com/ryanb/cancan for authorization: # config.authorize_with :cancan # Or use simple custom authorization rule: # config.authorize_with do # redirect_to root_path unless warden.user.is_admin? # end # Use a specific role for ActiveModel's :attr_acessible :attr_protected # Default is :default # current_user is accessible in the block if you want to make it user specific. # config.attr_accessible_role { :default } # ==> Global show view settings # Display empty fields in show views # config.compact_show_view = false # ==> Global list view settings # Number of default rows per-page: # config.default_items_per_page = 50 # ==> Included models # Add all excluded models here: # config.excluded_models << [Drug, Race, RiskFactor, School, Student, User] # Add models here if you want to go 'whitelist mode': # config.included_models << [Drug, Race, RiskFactor, School, Student, User] # Application wide tried label methods for models' instances # config.label_methods << [:description] # Default is [:name, :title] # ==> Global models configuration # config.models do # # Configuration here will affect all included models in all scopes, handle with care! # # list do # # Configuration here will affect all included models in list sections (same for show, export, edit, update, create) # # fields :name, :other_name do # # Configuration here will affect all fields named [:name, :other_name], in the list section, for all included models # end # # fields_of_type :date do # # Configuration here will affect all date fields, in the list section, for all included models. See README for a comprehensive type list. # end # end # end # # ==> Model specific configuration # Keep in mind that *all* configuration blocks are optional. # RailsAdmin will try his best to provide the best defaults for each section, for each field! # Try to override as few things as possible, in the most generic way. Try to avoid setting labels for models and attributes, use ActiveRecord I18n API instead. # Less code is better code! # config.model MyModel do # # Here goes your cross-section field configuration for ModelName. # object_label_method :name # Name of the method called for pretty printing an *instance* of ModelName # label 'My model' # Name of ModelName (smartly defaults to ActiveRecord's I18n API) # label_plural 'My models' # Same, plural # weight -1 # Navigation priority. Bigger is higher. # parent OtherModel # Set parent model for navigation. MyModel will be nested below. OtherModel will be on first position of the dropdown # navigation_label # Sets dropdown entry's name in navigation. Only for parents! # # Section specific configuration: # list do # filters [:id, :name] # Array of field names which filters should be shown by default in the table header # items_per_page 100 # Override default_items_per_page # sort_by :id # Sort column (default is primary key) # sort_reverse true # Sort direction (default is true for primary key, last created first) # # Here goes the fields configuration for the list view # end # show do # # Here goes the fields configuration for the show view # end # export do # # Here goes the fields configuration for the export view (CSV, yaml, XML) # end # edit do # # Here goes the fields configuration for the edit view (for create and update view) # end # create do # # Here goes the fields configuration for the create view, overriding edit section settings # end # update do # # Here goes the fields configuration for the update view, overriding edit section settings # end # end # fields configuration is described in the Readme, if you have other question, ask us on the mailing-list! # ==> Your models configuration, to help you get started! # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model Drug do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :name, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model Race do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :name, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model RiskFactor do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :status, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model School do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :name, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model Student do # # Found associations: # field :drug, :belongs_to_association # field :race, :belongs_to_association # field :school, :belongs_to_association # field :risk_factor, :belongs_to_association # field :updated_school, :belongs_to_association # field :deputy, :belongs_to_association # # Found columns: # field :id, :integer # field :first_name, :string # field :last_name, :string # field :id_number, :string # field :gender, :string # field :dob, :date # field :race_id, :integer # Hidden # field :street_number, :string # field :street_name, :string # field :address_2, :string # field :city, :string # field :zip_code, :string # field :phone, :string # field :cell_phone, :string # field :alt_name, :string # field :school_id, :integer # Hidden # field :updated_school_id, :integer # Hidden # field :grade, :string # field :vehicle, :string # field :associates, :string # field :crimes, :string # field :urn, :string # field :probation, :boolean # field :probation_status, :string # field :gang, :string # field :moniker, :string # field :drug_id, :integer # Hidden # field :programs, :text # field :notes, :text # field :risk_factor_id, :integer # Hidden # field :school_deputy_id, :integer # Hidden # field :created_at, :datetime # field :updated_at, :datetime # field :photo_file_name, :string # Hidden # field :photo_content_type, :string # Hidden # field :photo_file_size, :integer # Hidden # field :photo_updated_at, :datetime # Hidden # field :photo, :paperclip_file # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model User do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :email, :string # field :password, :password # field :password_confirmation, :password # field :reset_password_token, :string # Hidden # field :reset_password_sent_at, :datetime # field :remember_created_at, :datetime # field :sign_in_count, :integer # field :current_sign_in_at, :datetime # field :last_sign_in_at, :datetime # field :current_sign_in_ip, :string # field :last_sign_in_ip, :string # field :created_at, :datetime # field :updated_at, :datetime # field :first_name, :string # field :last_name, :string # field :school_deputy, :boolean # field :tip_deputy, :boolean # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end end # You made it this far? You're looking for something that doesn't exist! Add it to RailsAdmin and send us a Pull Request! Add redirect to home path for rails admin # ooooooooo. o8o oooo .o. .o8 o8o # `888 `Y88. `"' `888 .888. "888 `"' # 888 .d88' .oooo. oooo 888 .oooo.o .8"888. .oooo888 ooo. .oo. .oo. oooo ooo. .oo. # 888ooo88P' `P )88b `888 888 d88( "8 .8' `888. d88' `888 `888P"Y88bP"Y88b `888 `888P"Y88b # 888`88b. .oP"888 888 888 `"Y88b. .88ooo8888. 888 888 888 888 888 888 888 888 # 888 `88b. d8( 888 888 888 o. )88b .8' `888. 888 888 888 888 888 888 888 888 # o888o o888o `Y888""8o o888o o888o 8""888P' o88o o8888o `Y8bod88P" o888o o888o o888o o888o o888o o888o # RailsAdmin config file. Generated on October 06, 2011 19:07 # See github.com/sferik/rails_admin for more informations RailsAdmin.config do |config| config.current_user_method { current_user } # auto-generated config.main_app_name { ['SCV Sheriff', 'Admin'] } # auto-generated # ==> Authentication (before_filter) # This is run inside the controller instance so you can setup any authentication you need to. # By default, the authentication will run via warden if available. # and will run on the default user scope. # If you use devise, this will authenticate the same as authenticate_user! # Example Devise admin # RailsAdmin.config do |config| config.authenticate_with do authenticate_user! redirect_to main_app.home_index_path, :alert =>"You don't have access to this section" unless current_user.admin? end # end # Example Custom Warden # RailsAdmin.config do |config| # config.authenticate_with do # warden.authenticate! :scope => :paranoid # end # end # ==> Authorization # Use cancan https://github.com/ryanb/cancan for authorization: # config.authorize_with :cancan # Or use simple custom authorization rule: # config.authorize_with do # redirect_to root_path unless warden.user.is_admin? # end # Use a specific role for ActiveModel's :attr_acessible :attr_protected # Default is :default # current_user is accessible in the block if you want to make it user specific. # config.attr_accessible_role { :default } # ==> Global show view settings # Display empty fields in show views # config.compact_show_view = false # ==> Global list view settings # Number of default rows per-page: # config.default_items_per_page = 50 # ==> Included models # Add all excluded models here: # config.excluded_models << [Drug, Race, RiskFactor, School, Student, User] # Add models here if you want to go 'whitelist mode': # config.included_models << [Drug, Race, RiskFactor, School, Student, User] # Application wide tried label methods for models' instances # config.label_methods << [:description] # Default is [:name, :title] # ==> Global models configuration # config.models do # # Configuration here will affect all included models in all scopes, handle with care! # # list do # # Configuration here will affect all included models in list sections (same for show, export, edit, update, create) # # fields :name, :other_name do # # Configuration here will affect all fields named [:name, :other_name], in the list section, for all included models # end # # fields_of_type :date do # # Configuration here will affect all date fields, in the list section, for all included models. See README for a comprehensive type list. # end # end # end # # ==> Model specific configuration # Keep in mind that *all* configuration blocks are optional. # RailsAdmin will try his best to provide the best defaults for each section, for each field! # Try to override as few things as possible, in the most generic way. Try to avoid setting labels for models and attributes, use ActiveRecord I18n API instead. # Less code is better code! # config.model MyModel do # # Here goes your cross-section field configuration for ModelName. # object_label_method :name # Name of the method called for pretty printing an *instance* of ModelName # label 'My model' # Name of ModelName (smartly defaults to ActiveRecord's I18n API) # label_plural 'My models' # Same, plural # weight -1 # Navigation priority. Bigger is higher. # parent OtherModel # Set parent model for navigation. MyModel will be nested below. OtherModel will be on first position of the dropdown # navigation_label # Sets dropdown entry's name in navigation. Only for parents! # # Section specific configuration: # list do # filters [:id, :name] # Array of field names which filters should be shown by default in the table header # items_per_page 100 # Override default_items_per_page # sort_by :id # Sort column (default is primary key) # sort_reverse true # Sort direction (default is true for primary key, last created first) # # Here goes the fields configuration for the list view # end # show do # # Here goes the fields configuration for the show view # end # export do # # Here goes the fields configuration for the export view (CSV, yaml, XML) # end # edit do # # Here goes the fields configuration for the edit view (for create and update view) # end # create do # # Here goes the fields configuration for the create view, overriding edit section settings # end # update do # # Here goes the fields configuration for the update view, overriding edit section settings # end # end # fields configuration is described in the Readme, if you have other question, ask us on the mailing-list! # ==> Your models configuration, to help you get started! # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model Drug do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :name, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model Race do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :name, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model RiskFactor do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :status, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model School do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :name, :string # field :created_at, :datetime # field :updated_at, :datetime # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model Student do # # Found associations: # field :drug, :belongs_to_association # field :race, :belongs_to_association # field :school, :belongs_to_association # field :risk_factor, :belongs_to_association # field :updated_school, :belongs_to_association # field :deputy, :belongs_to_association # # Found columns: # field :id, :integer # field :first_name, :string # field :last_name, :string # field :id_number, :string # field :gender, :string # field :dob, :date # field :race_id, :integer # Hidden # field :street_number, :string # field :street_name, :string # field :address_2, :string # field :city, :string # field :zip_code, :string # field :phone, :string # field :cell_phone, :string # field :alt_name, :string # field :school_id, :integer # Hidden # field :updated_school_id, :integer # Hidden # field :grade, :string # field :vehicle, :string # field :associates, :string # field :crimes, :string # field :urn, :string # field :probation, :boolean # field :probation_status, :string # field :gang, :string # field :moniker, :string # field :drug_id, :integer # Hidden # field :programs, :text # field :notes, :text # field :risk_factor_id, :integer # Hidden # field :school_deputy_id, :integer # Hidden # field :created_at, :datetime # field :updated_at, :datetime # field :photo_file_name, :string # Hidden # field :photo_content_type, :string # Hidden # field :photo_file_size, :integer # Hidden # field :photo_updated_at, :datetime # Hidden # field :photo, :paperclip_file # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end # All fields marked as 'hidden' won't be shown anywhere in the rails_admin unless you mark them as visible. # There can be different reasons for that: # - belongs_to _id and _type (polymorphic) columns are hidden in favor of their associations # - associations are hidden if they have no matchable model found (model not included or non-existant) # - they are part of a bigger plan in a plugin (Devise/Paperclip) and hidden by contract # Some fields may be hidden depending on the section, if they aren't deemed suitable for display or edition on that section # - non-editable columns (:id, :created_at, ..) in edit sections # - has_many/has_one associations in list section (hidden by default for performance reasons) # Fields may also be marked as read_only (and thus not editable) if they are not mass-assignable by current_user # config.model User do # # Found associations: # field :students, :has_many_association # # Found columns: # field :id, :integer # field :email, :string # field :password, :password # field :password_confirmation, :password # field :reset_password_token, :string # Hidden # field :reset_password_sent_at, :datetime # field :remember_created_at, :datetime # field :sign_in_count, :integer # field :current_sign_in_at, :datetime # field :last_sign_in_at, :datetime # field :current_sign_in_ip, :string # field :last_sign_in_ip, :string # field :created_at, :datetime # field :updated_at, :datetime # field :first_name, :string # field :last_name, :string # field :school_deputy, :boolean # field :tip_deputy, :boolean # # Sections: # list do; end # export do; end # show do; end # edit do; end # create do; end # update do; end # end end # You made it this far? You're looking for something that doesn't exist! Add it to RailsAdmin and send us a Pull Request!
[RailsAdmin::Config::Actions::MemoryUsage, RailsAdmin::Config::Actions::DiskUsage, RailsAdmin::Config::Actions::SendToFlow, RailsAdmin::Config::Actions::LoadModel, RailsAdmin::Config::Actions::ShutdownModel, RailsAdmin::Config::Actions::SwitchNavigation, RailsAdmin::Config::Actions::DataType, RailsAdmin::Config::Actions::Import, #RailsAdmin::Config::Actions::EdiExport, RailsAdmin::Config::Actions::ImportSchema, RailsAdmin::Config::Actions::DeleteAll, RailsAdmin::Config::Actions::TranslatorUpdate, RailsAdmin::Config::Actions::Convert, RailsAdmin::Config::Actions::DeleteLibrary, RailsAdmin::Config::Actions::SimpleShare, RailsAdmin::Config::Actions::BulkShare, RailsAdmin::Config::Actions::Pull, RailsAdmin::Config::Actions::RetryTask, RailsAdmin::Config::Actions::UploadFile, RailsAdmin::Config::Actions::DownloadFile, RailsAdmin::Config::Actions::ProcessFlow, RailsAdmin::Config::Actions::BuildGem, RailsAdmin::Config::Actions::Run, RailsAdmin::Config::Actions::Authorize, RailsAdmin::Config::Actions::SimpleDeleteDataType, RailsAdmin::Config::Actions::BulkDeleteDataType, RailsAdmin::Config::Actions::SimpleGenerate, RailsAdmin::Config::Actions::BulkGenerate, RailsAdmin::Config::Actions::SimpleExpand, RailsAdmin::Config::Actions::BulkExpand, RailsAdmin::Config::Actions::Records, RailsAdmin::Config::Actions::SwitchScheduler, RailsAdmin::Config::Actions::SimpleExport, RailsAdmin::Config::Actions::Schedule, RailsAdmin::Config::Actions::Submit, RailsAdmin::Config::Actions::DeleteCollection].each { |a| RailsAdmin::Config::Actions.register(a) } RailsAdmin::Config::Actions.register(:export, RailsAdmin::Config::Actions::BulkExport) RailsAdmin::Config::Fields::Types.register(RailsAdmin::Config::Fields::Types::JsonValue) RailsAdmin::Config::Fields::Types.register(RailsAdmin::Config::Fields::Types::JsonSchema) RailsAdmin::Config::Fields::Types.register(RailsAdmin::Config::Fields::Types::StorageFile) { config: { mode: 'css', theme: 'neo', }, assets: { mode: '/assets/codemirror/modes/css.js', theme: '/assets/codemirror/themes/neo.css', } }.each { |option, configuration| RailsAdmin::Config::Fields::Types::CodeMirror.register_instance_option(option) { configuration } } RailsAdmin.config do |config| ## == PaperTrail == # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration config.authenticate_with do warden.authenticate! scope: :user end config.current_user_method { current_user } config.audit_with :mongoid_audit config.authorize_with :cancan config.excluded_models += [Setup::BaseOauthAuthorization, Setup::AwsAuthorization] config.actions do dashboard # mandatory # memory_usage # disk_usage index # mandatory new { except [Setup::Event, Setup::DataType, Setup::Authorization, Setup::BaseOauthProvider] } import import_schema translator_update convert export bulk_delete show run edit simple_share bulk_share build_gem pull upload_file download_file load_model shutdown_model process_flow authorize simple_generate bulk_generate simple_expand bulk_expand records switch_navigation switch_scheduler simple_export schedule retry_task submit simple_delete_data_type bulk_delete_data_type delete delete_library delete_collection #show_in_app send_to_flow delete_all data_type # history_index do # only [Setup::DataType, Setup::Webhook, Setup::Flow, Setup::Schema, Setup::Event, Setup::Connection, Setup::ConnectionRole, Setup::Library] # end # history_show do # only [Setup::DataType, Setup::Webhook, Setup::Flow, Setup::Schema, Setup::Event, Setup::Connection, Setup::ConnectionRole, Setup::Notification, Setup::Library] # end end config.model Setup::Validator do visible false end config.model Setup::Library do navigation_label 'Data Definitions' weight -16 configure :name do read_only { !bindings[:object].new_record? } help '' end edit do field :name field :slug end show do field :name field :slug field :schemas field :data_types field :_id field :created_at #field :creator field :updated_at #field :updater end fields :name, :slug, :schemas, :data_types end config.model Setup::Schema do object_label_method { :custom_title } navigation_label 'Data Definitions' weight -18 edit do field :library do read_only { !bindings[:object].new_record? } inline_edit false end field :uri do read_only { !bindings[:object].new_record? } html_attributes do { cols: '74', rows: '1' } end end field :schema, :code_mirror do html_attributes do { cols: '74', rows: '15' } end end field :schema_data_type do inline_edit false inline_add false end end show do field :library field :uri field :schema do pretty_value do pretty_value = if json = JSON.parse(value) rescue nil "<code class='json'>#{JSON.pretty_generate(json)}</code>" elsif xml = Nokogiri::XML(value) rescue nil "<code class='xml'>#{xml.to_xml}</code>" else value end "<pre>#{pretty_value}</pre>".html_safe end end field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :library, :uri, :schema_data_type end config.model Setup::DataType do label 'Data type' label_plural 'Data types' object_label_method { :custom_title } navigation_label 'Data Definitions' weight -17 group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :slug configure :storage_size, :decimal do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = bindings[:controller].instance_variable_get(:@objects).collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :title field :before_save_callbacks field :records_methods field :data_type_methods end list do field :title field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::DataType.fields[:used_memory.to_s].type.new(Setup::DataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::DataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size end show do field :title field :name field :slug field :activated field :schema do pretty_value do pretty_value = if json = JSON.pretty_generate(value) rescue nil "<code class='json'>#{json}</code>" else value end "<pre>#{pretty_value}</pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end fields :title, :name, :used_memory end config.model Setup::EdiValidator do object_label_method { :custom_title } label 'EDI Validators' navigation_label 'Data Definitions' fields :namespace, :name, :schema_data_type, :content_type end config.model Setup::AlgorithmValidator do object_label_method { :custom_title } navigation_label 'Data Definitions' fields :namespace, :name, :algorithm end config.model Setup::FileDataType do object_label_method { :custom_title } group :content do label 'Content' end group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :library do associated_collection_scope do library = (obj = bindings[:object]).library Proc.new { |scope| if library scope.where(id: library.id) else scope end } end end configure :used_memory do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::SchemaDataType.fields[:used_memory.to_s].type.new(Setup::SchemaDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::SchemaDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end configure :storage_size, :decimal do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = bindings[:controller].instance_variable_get(:@objects).collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe end read_only true end configure :validators do group :content inline_add false end configure :schema_data_type do group :content inline_add false inline_edit false end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :library field :title field :name field :slug field :validators field :schema_data_type field :before_save_callbacks field :records_methods field :data_type_methods end list do field :title field :name field :slug field :validators field :schema_data_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::SchemaDataType.fields[:used_memory.to_s].type.new(Setup::SchemaDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::SchemaDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size end show do field :title field :name field :slug field :activated field :validators field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end end config.model Setup::SchemaDataType do group :behavior do label 'Behavior' active false end object_label_method { :custom_title } navigation_label 'Data Definitions' weight -17 register_instance_option(:after_form_partials) do %w(shutdown_and_reload) end configure :title configure :name do read_only { !bindings[:object].new_record? } end configure :schema, :code_mirror do html_attributes do report = bindings[:object].shutdown(report_only: true) reload = (report[:reloaded].collect(&:data_type) + report[:destroyed].collect(&:data_type)).uniq bindings[:object].instance_variable_set(:@_to_reload, reload) { cols: '74', rows: '15' } end # pretty_value do # "<pre><code class='json'>#{JSON.pretty_generate(value)}</code></pre>".html_safe # end end configure :storage_size, :decimal do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = bindings[:controller].instance_variable_get(:@objects).collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe end end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :library field :title field :name field :slug field :schema, :json_schema do help { 'Required' } end field :before_save_callbacks field :records_methods field :data_type_methods end list do field :library field :title field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::SchemaDataType.fields[:used_memory.to_s].type.new(Setup::SchemaDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::SchemaDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size end show do field :library field :title field :name field :slug field :activated field :schema do pretty_value do "<pre><code class='ruby'>#{JSON.pretty_generate(value)}</code></pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end end config.model Setup::Connection do object_label_method { :custom_title } weight -15 group :credentials do label 'Credentials' end configure :key, :string do visible { bindings[:view]._current_user.has_role? :admin } html_attributes do { maxlength: 30, size: 30 } end group :credentials end configure :token, :text do visible { bindings[:view]._current_user.has_role? :admin } html_attributes do { cols: '50', rows: '1' } end group :credentials end configure :authorization do group :credentials inline_edit false visible { bindings[:view]._current_user.has_role? :admin } end configure :authorization_handler do group :credentials visible { bindings[:view]._current_user.has_role? :admin } end group :parameters do label 'Parameters & Headers' end configure :parameters do group :parameters visible { bindings[:view]._current_user.has_role? :admin } end configure :headers do group :parameters visible { bindings[:view]._current_user.has_role? :admin } end configure :template_parameters do group :parameters visible { bindings[:view]._current_user.has_role? :admin } end show do field :namespace field :name field :url field :key field :token field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :url, :key, :token, :authorization, :authorization_handler, :parameters, :headers, :template_parameters end config.model Setup::Parameter do object_label_method { :to_s } edit do field :key field :value field :description field :metadata, :json_value end end config.model Setup::ConnectionRole do object_label_method { :custom_title } weight -14 configure :name, :string do help 'Requiered.' html_attributes do { maxlength: 50, size: 50 } end end configure :webhooks do nested_form false end configure :connections do nested_form false end modal do field :namespace field :name field :webhooks field :connections end show do field :namespace field :name field :webhooks field :connections field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :webhooks, :connections end config.model Setup::Webhook do object_label_method { :custom_title } weight -13 configure :metadata, :json_value group :credentials do label 'Credentials' end configure :authorization do group :credentials inline_edit false visible { bindings[:view]._current_user.has_role? :admin } end configure :authorization_handler do group :credentials visible { bindings[:view]._current_user.has_role? :admin } end group :parameters do label 'Parameters & Headers' end configure :path, :string do help 'Requiered. Path of the webhook relative to connection URL.' html_attributes do { maxlength: 255, size: 100 } end end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end show do field :namespace field :name field :path field :method field :description field :metadata, :json_value field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :path, :method, :description, :metadata, :authorization, :authorization_handler, :parameters, :headers, :template_parameters end config.model Setup::Task do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::FlowExecution do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :flow, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::DataTypeGeneration do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::DataTypeExpansion do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Translation do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::DataImport do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end fields :translator, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::SchemasImport do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :library, :base_uri, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Deletion do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :deletion_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.contextualized_label(:menu), v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end edit do field :description end fields :deletion_model, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::AlgorithmExecution do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :algorithm, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Submission do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :webhook, :connection, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Notification do navigation_label 'Monitor' object_label_method { :label } configure :created_at configure :type do pretty_value do color = case bindings[:object].type when :info 'green' when :notice 'blue' when :warning 'orange' else 'red' end "<label style='color:#{color}'>#{value.to_s.capitalize}</label>".html_safe end end configure :message do pretty_value do color = case bindings[:object].type when :info 'green' when :notice 'blue' when :warning 'orange' else 'red' end "<label style='color:#{color}'>#{value}</label>".html_safe end end configure :attachment, :storage_file fields :created_at, :type, :message, :attachment, :task end config.model Setup::Flow do object_label_method { :custom_title } register_instance_option(:form_synchronized) do [:custom_data_type, :data_type_scope, :scope_filter, :scope_evaluator, :lot_size, :connection_role, :webhook, :response_translator, :response_data_type] end edit do field :namespace field :name field :event do inline_edit false inline_add false end field :translator do help 'Required' end field :custom_data_type do inline_edit false inline_add false visible do if (f = bindings[:object]).custom_data_type.present? f.nil_data_type = false end if f.translator.present? && f.translator.data_type.nil? && !f.nil_data_type f.instance_variable_set(:@selecting_data_type, f.custom_data_type = f.event && f.event.try(:data_type)) unless f.data_type f.nil_data_type = f.translator.type == :Export && (params = (controller = bindings[:controller]).params) && (params = params[controller.abstract_model.param_key]) && params[:custom_data_type_id].blank? && params.keys.include?(:custom_data_type_id.to_s) true else false end end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) 'Source data type' else 'Target data type' end else 'Data type' end end help do if bindings[:object].nil_data_type '' elsif (translator = bindings[:object].translator) && [:Export, :Conversion].include?(translator.type) 'Optional' else 'Required' end end end field :nil_data_type do visible { bindings[:object].nil_data_type } label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) 'No source data type' else 'No target data type' end else 'No data type' end end end field :data_type_scope do visible do bindings[:controller].instance_variable_set(:@_data_type, bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'translator_id') (f = bindings[:object]).translator.present? && f.translator.type != :Import && f.data_type && !f.instance_variable_get(:@selecting_data_type) end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) 'Source scope' else 'Target scope' end else 'Data type scope' end end help 'Required' end field :scope_filter do visible { bindings[:object].scope_symbol == :filtered } partial 'form_triggers' help false end field :scope_evaluator do inline_add false inline_edit false visible { bindings[:object].scope_symbol == :evaluation } associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end help 'Required' end field :lot_size do visible { (f = bindings[:object]).translator.present? && f.translator.type == :Export && !f.nil_data_type && f.data_type_scope && f.scope_symbol != :event_source } end field :webhook do visible { (translator = (f = bindings[:object]).translator) && (translator.type == :Import || (translator.type == :Export && (bindings[:object].data_type_scope.present? || f.nil_data_type))) } help 'Required' end field :connection_role do visible { (translator = (f = bindings[:object]).translator) && (translator.type == :Import || (translator.type == :Export && (bindings[:object].data_type_scope.present? || f.nil_data_type))) } help 'Optional' end field :response_translator do visible { (translator = (f = bindings[:object]).translator) && (translator.type == :Export && (bindings[:object].data_type_scope.present? || f.nil_data_type)) && f.ready_to_save? } associated_collection_scope do Proc.new { |scope| scope.where(type: :Import) } end end field :response_data_type do inline_edit false inline_add false visible { (response_translator = bindings[:object].response_translator) && response_translator.type == :Import && response_translator.data_type.nil? } help '' end field :discard_events do visible { (((obj = bindings[:object]).translator && obj.translator.type == :Import) || obj.response_translator.present?) && obj.ready_to_save? } help "Events won't be fired for created or updated records if checked" end field :active do visible { bindings[:object].ready_to_save? } end field :notify_request do visible { (obj = bindings[:object]).translator && [:Import, :Export].include?(obj.translator.type) && obj.ready_to_save? } help 'Track request via notifications if checked' end field :notify_response do visible { (obj = bindings[:object]).translator && [:Import, :Export].include?(obj.translator.type) && obj.ready_to_save? } help 'Track responses via notification if checked' end field :after_process_callbacks do visible { bindings[:object].ready_to_save? } help 'Algorithms executed after flow processing, execution state is supplied as argument' end end show do field :namespace field :name field :active field :event field :translator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :active, :event, :translator end config.model Setup::Event do object_label_method { :custom_title } edit do field :namespace field :name end show do field :namespace field :name field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name end config.model Setup::Observer do object_label_method { :custom_title } edit do field :namespace field :name field :data_type do inline_add false inline_edit false associated_collection_scope do data_type = bindings[:object].data_type Proc.new { |scope| if data_type scope.where(id: data_type.id) else scope end } end help 'Required' end field :trigger_evaluator do visible { (obj = bindings[:object]).data_type.blank? || obj.trigger_evaluator.present? || obj.triggers.nil? } associated_collection_scope do Proc.new { |scope| scope.all.or(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :triggers do visible do bindings[:controller].instance_variable_set(:@_data_type, data_type = bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'data_type_id') data_type.present? && !bindings[:object].trigger_evaluator.present? end partial 'form_triggers' help false end end show do field :namespace field :name field :data_type field :triggers field :trigger_evaluator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :data_type, :triggers, :trigger_evaluator end config.model Setup::Scheduler do object_label_method { :custom_title } edit do field :namespace field :name field :scheduling_method field :expression do visible { bindings[:object].scheduling_method.present? } label do case bindings[:object].scheduling_method when :Once 'Date and time' when :Periodic 'Duration' when :CRON 'CRON Expression' else 'Expression' end end help do case bindings[:object].scheduling_method when :Once 'Select a date and a time' when :Periodic 'Type a time duration' when :CRON 'Type a CRON Expression' else 'Expression' end end partial { bindings[:object].scheduling_method == :Once ? 'form_datetime_wrapper' : 'form_text' } html_attributes do { rows: '1' } end end end show do field :namespace field :name field :expression field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :scheduling_method, :expression, :activated end config.model Setup::Translator do object_label_method { :custom_title } register_instance_option(:form_synchronized) do [:source_data_type, :target_data_type, :transformation, :target_importer, :source_exporter, :discard_chained_records] end edit do field :namespace field :name field :type field :source_data_type do inline_edit false inline_add false visible { [:Export, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :target_data_type do inline_edit false inline_add false visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :discard_events do visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help "Events won't be fired for created or updated records if checked" end field :style do visible { bindings[:object].type.present? } help 'Required' end field :bulk_source do visible { bindings[:object].type == :Export && bindings[:object].style.present? && bindings[:object].source_bulkable? } end field :mime_type do label 'MIME type' visible { bindings[:object].type == :Export && bindings[:object].style.present? } end field :file_extension do visible { bindings[:object].type == :Export && !bindings[:object].file_extension_enum.empty? } help { "Extensions for #{bindings[:object].mime_type}" } end field :source_handler do visible { (t = bindings[:object]).style.present? && (t.type == :Update || (t.type == :Conversion && t.style == 'ruby')) } help { 'Handle sources on transformation' } end field :transformation, :code_mirror do visible { bindings[:object].style.present? && bindings[:object].style != 'chain' } help { 'Required' } html_attributes do { cols: '74', rows: '15' } end end field :source_exporter do inline_add { bindings[:object].source_exporter.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type } help 'Required' associated_collection_scope do data_type = bindings[:object].source_data_type Proc.new { |scope| scope.all(type: :Conversion, source_data_type: data_type) } end end field :target_importer do inline_add { bindings[:object].target_importer.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help 'Required' associated_collection_scope do translator = bindings[:object] source_data_type = if translator.source_exporter translator.source_exporter.target_data_type else translator.source_data_type end target_data_type = bindings[:object].target_data_type Proc.new { |scope| scope = scope.all(type: :Conversion, source_data_type: source_data_type, target_data_type: target_data_type) } end end field :discard_chained_records do visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help "Chained records won't be saved if checked" end end show do field :namespace field :name field :type field :source_data_type field :bulk_source field :target_data_type field :discard_events field :style field :mime_type field :file_extension field :transformation do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :source_exporter field :target_importer field :discard_chained_records field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :type, :style, :transformation end config.model Setup::SharedName do visible { false } navigation_label 'Collections' fields :name, :owners end config.model Script do navigation_label 'Administration' configure :code, :code_mirror do help { 'Required' } pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end fields :name, :description, :code end config.model Setup::SharedCollection do register_instance_option(:discard_submit_buttons) do !(a = bindings[:action]) || a.key != :edit end navigation_label 'Collections' object_label_method { :versioned_name } weight -19 edit do field :image do visible { !bindings[:object].new_record? } end field :name do required { true } end field :shared_version do required { true } end field :authors field :summary field :description, :froala do end field :source_collection do visible { !((source_collection = bindings[:object].source_collection) && source_collection.new_record?) } inline_edit false inline_add false associated_collection_scope do source_collection = (obj = bindings[:object]).source_collection Proc.new { |scope| if obj.new_record? scope.where(id: source_collection ? source_collection.id : nil) else scope end } end end field :connections do inline_add false read_only do !bindings[:object].instance_variable_get(:@_selecting_connections) end help do nil end pretty_value do if bindings[:object].connections.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[connection_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No connection selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && obj.source_collection && obj.source_collection.connections.present? end associated_collection_scope do source_collection = bindings[:object].source_collection connections = (source_collection && source_collection.connections) || [] Proc.new { |scope| scope.any_in(id: connections.collect { |connection| connection.id }) } end end field :dependencies do inline_add false read_only do !bindings[:object].instance_variable_get(:@_selecting_dependencies) end help do nil end pretty_value do if bindings[:object].dependencies.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[dependency_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No dependencies selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) end end field :pull_parameters do visible do if !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && !obj.instance_variable_get(:@_selecting_connections) && (pull_parameters_enum = obj.enum_for_pull_parameters).present? bindings[:controller].instance_variable_set(:@shared_parameter_enum, pull_parameters_enum) true else false end end end end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :category field :summary field :description do pretty_value do value.html_safe end end field :authors field :dependencies field :_id field :created_at field :updated_at end list do field :image do thumb_method :icon end field :name do pretty_value do bindings[:object].versioned_name end end field :category field :authors field :summary field :dependencies end end config.model Setup::CollectionAuthor do object_label_method { :label } end config.model Setup::CollectionPullParameter do object_label_method { :label } field :label field :parameter, :enum do enum do bindings[:controller].instance_variable_get(:@shared_parameter_enum) || [bindings[:object].parameter] end end edit do field :label field :parameter end show do field :label field :parameter field :created_at #field :creator field :updated_at end fields :label, :parameter end config.model Setup::CollectionData do object_label_method { :label } end config.model Setup::Collection do navigation_label 'Collections' weight -19 group :setup do label 'Setup objects' active true end group :data do label 'Data' active false end configure :flows do group :setup end configure :connection_roles do group :setup end configure :translators do group :setup end configure :events do group :setup end configure :libraries do group :setup end configure :custom_validators do group :setup end configure :algorithms do group :setup end configure :webhooks do group :setup end configure :connections do group :setup end configure :authorizations do group :setup end configure :oauth_providers do group :setup end configure :oauth_clients do group :setup end configure :oauth2_scopes do group :setup end configure :data do group :data end show do field :image field :name field :flows field :connection_roles field :translators field :events field :libraries field :custom_validators field :algorithms field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :image do thumb_method :icon end field :name field :flows field :connection_roles field :translators field :events field :libraries field :custom_validators field :algorithms field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data end end config.model Setup::CustomValidator do visible false end config.model Setup::Integration do edit do field :name field :pull_connection field :pull_event do inline_add { false } inline_edit { false } end field :data_type field :receiver_connection end show do field :name field :pull_connection field :pull_flow field :pull_event field :pull_translator field :data_type field :send_translator field :send_flow field :receiver_connection end fields :name, :pull_connection, :pull_flow, :pull_event, :pull_translator, :data_type, :send_translator, :send_flow, :receiver_connection end config.model Setup::Algorithm do object_label_method { :custom_title } edit do field :namespace field :name field :description field :parameters field :code, :code_mirror do help { 'Required' } end field :call_links do visible { bindings[:object].call_links.present? } end end show do field :namespace field :name field :description field :parameters field :code do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :_id end fields :namespace, :name, :description, :parameters, :call_links end config.model Setup::CallLink do edit do field :name do read_only true help { nil } label 'Call name' end field :link do inline_add false inline_edit false help { nil } end end fields :name, :link end config.model Role do navigation_label 'Administration' fields :name, :users end config.model User do navigation_label 'Administration' object_label_method { :label } group :credentials do label 'Credentials' active true end group :activity do label 'Activity' active true end configure :name configure :email configure :roles configure :account do read_only { true } end configure :password do group :credentials end configure :password_confirmation do group :credentials end configure :key do group :credentials end configure :authentication_token do group :credentials end configure :confirmed_at do group :activity end configure :sign_in_count do group :activity end configure :current_sign_in_at do group :activity end configure :last_sign_in_at do group :activity end configure :current_sign_in_ip do group :activity end configure :last_sign_in_ip do group :activity end edit do field :picture field :name field :email do visible { Account.current.super_admin? } end field :roles do visible { Account.current.super_admin? } end field :account do label { Account.current.super_admin? ? 'Account' : 'Account settings' } help { nil } end field :password do visible { Account.current.super_admin? } end field :password_confirmation do visible { Account.current.super_admin? } end field :key do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :authentication_token do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :confirmed_at do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :sign_in_count do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :current_sign_in_at do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :last_sign_in_at do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :current_sign_in_ip do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :last_sign_in_ip do visible { !bindings[:object].new_record? && Account.current.super_admin? } end end show do field :picture field :name field :email field :account field :roles field :key field :authentication_token field :sign_in_count field :current_sign_in_at field :last_sign_in_at field :current_sign_in_ip field :last_sign_in_ip end fields :picture, :name, :email, :account, :roles, :key, :authentication_token, :authentication_token, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip end config.model Account do navigation_label 'Administration' object_label_method { :label } configure :_id do visible { Account.current.super_admin? } end configure :name do visible { Account.current.super_admin? } end configure :owner do read_only { !Account.current.super_admin? } help { nil } end configure :tenant_account do visible { Account.current.super_admin? } end configure :number do visible { Account.current.super_admin? } end configure :users do visible { Account.current.super_admin? } end configure :notification_level fields :_id, :name, :owner, :tenant_account, :number, :users, :notification_level end config.model Setup::SharedName do navigation_label 'Administration' fields :name, :owners end config.model Script do navigation_label 'Administration' edit do field :name field :description field :code, :code_mirror end show do field :name field :description field :code do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end end fields :name, :description, :code end config.model CenitToken do navigation_label 'Administration' end config.model Setup::BaseOauthProvider do object_label_method { :custom_title } label 'Provider' navigation_label 'OAuth' configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :parameters, :clients, :tenant, :shared end config.model Setup::OauthProvider do object_label_method { :custom_title } configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :request_token_endpoint, :parameters, :tenant, :shared end config.model Setup::Oauth2Provider do object_label_method { :custom_title } configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :parameters, :scope_separator, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :shared end config.model Setup::OauthParameter do navigation_label 'OAuth' object_label_method { :to_s } fields :key, :value end config.model Setup::OauthClient do object_label_method { :custom_title } navigation_label 'OAuth' configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end configure :identifier do pretty_value do if Account.current.super_admin? || Account.current.users.collect(&:id).include?(bindings[:object].creator_id) value else '<i class="icon-lock"/>'.html_safe end end end configure :secret do pretty_value do if Account.current.super_admin? || Account.current.users.collect(&:id).include?(bindings[:object].creator_id) value else '<i class="icon-lock"/>'.html_safe end end end fields :namespace, :name, :provider, :identifier, :secret, :tenant, :shared end config.model Setup::Oauth2Scope do object_label_method { :custom_title } navigation_label 'OAuth' configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end fields :provider, :name, :description, :tenant, :shared end config.model Setup::Authorization do fields :namespace, :name end config.model Setup::OauthAuthorization do parent Setup::Authorization edit do field :namespace field :name field :provider do inline_add false inline_edit false associated_collection_scope do provider = (obj = bindings[:object]) && obj.provider Proc.new { |scope| if provider scope.any_in(id: provider.id) else scope.any_in(_type: Setup::OauthProvider.to_s) end } end end field :client do inline_add false inline_edit false visible do if ((obj = bindings[:object]) && obj.provider).present? obj.client = obj.provider.clients.first if obj.client.blank? true else false end end associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :access_token_secret do group :credentials end configure :realm do group :credentials end show do field :namespace field :name field :provider field :client field :access_token field :access_token_secret field :realm field :token_span field :authorized_at end fields :namespace, :name, :provider, :client end config.model Setup::Oauth2Authorization do parent Setup::Authorization edit do field :namespace field :name field :provider do inline_add false inline_edit false associated_collection_scope do provider = (obj = bindings[:object]) && obj.provider Proc.new { |scope| if provider scope.any_in(id: provider.id) else scope.any_in(_type: Setup::Oauth2Provider.to_s) end } end end field :client do inline_add false inline_edit false visible do if ((obj = bindings[:object]) && obj.provider).present? obj.client = obj.provider.clients.first if obj.client.blank? true else false end end associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end field :scopes do visible { ((obj = bindings[:object]) && obj.provider).present? } associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :refresh_token do group :credentials end configure :token_type do group :credentials end show do field :namespace field :name field :provider field :client field :scopes field :token_type field :access_token field :token_span field :authorized_at field :refresh_token end fields :namespace, :name, :provider, :client, :scopes end config.model Setup::AwsAuthorization do edit do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version end group :credentials do label 'Credentials' end configure :aws_access_key do group :credentials end configure :aws_secret_key do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version end fields :namespace, :name, :aws_access_key, :aws_secret_key, :seller, :merchant, :markets, :signature_method, :signature_version end config.model Setup::BasicAuthorization do edit do field :namespace field :name field :username field :password end group :credentials do label 'Credentials' end configure :username do group :credentials end configure :password do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version end fields :namespace, :name, :username, :password end config.model Setup::Raml do configure :raml_references do visible { bindings[:view]._current_user.has_role? :admin } end show do field :api_name field :api_version field :repo field :raml_doc field :raml_references end edit do field :api_name field :api_version field :repo field :raml_doc field :raml_references end fields :api_name, :api_version, :repo, :raml_doc, :raml_references end config.model Setup::RamlReference do object_label_method { :to_s } edit do field :path field :content end fields :path, :content end config.model Setup::Storage do object_label_method { :label } configure :filename do label 'File name' pretty_value { bindings[:object].storage_name } end configure :length do label 'Size' pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_length) bindings[:controller].instance_variable_set(:@max_length, max = bindings[:controller].instance_variable_get(:@objects).collect { |storage| storage.length }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].length }).html_safe end end configure :storer_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.label, v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end configure :storer_object do label 'Object' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value.class) am = amc.abstract_model wording = value.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, value)) (can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: value.id), class: 'pjax') : wording).html_safe end end end configure :storer_property do label 'Property' end configure :chunks fields :storer_model, :storer_object, :storer_property, :filename, :contentType, :length, :chunks end config.model Setup::DelayedMessage do navigation_label 'Administration' end config.model Setup::SystemNotification do navigation_label 'Administration' end end Fixing storage view [RailsAdmin::Config::Actions::MemoryUsage, RailsAdmin::Config::Actions::DiskUsage, RailsAdmin::Config::Actions::SendToFlow, RailsAdmin::Config::Actions::LoadModel, RailsAdmin::Config::Actions::ShutdownModel, RailsAdmin::Config::Actions::SwitchNavigation, RailsAdmin::Config::Actions::DataType, RailsAdmin::Config::Actions::Import, #RailsAdmin::Config::Actions::EdiExport, RailsAdmin::Config::Actions::ImportSchema, RailsAdmin::Config::Actions::DeleteAll, RailsAdmin::Config::Actions::TranslatorUpdate, RailsAdmin::Config::Actions::Convert, RailsAdmin::Config::Actions::DeleteLibrary, RailsAdmin::Config::Actions::SimpleShare, RailsAdmin::Config::Actions::BulkShare, RailsAdmin::Config::Actions::Pull, RailsAdmin::Config::Actions::RetryTask, RailsAdmin::Config::Actions::UploadFile, RailsAdmin::Config::Actions::DownloadFile, RailsAdmin::Config::Actions::ProcessFlow, RailsAdmin::Config::Actions::BuildGem, RailsAdmin::Config::Actions::Run, RailsAdmin::Config::Actions::Authorize, RailsAdmin::Config::Actions::SimpleDeleteDataType, RailsAdmin::Config::Actions::BulkDeleteDataType, RailsAdmin::Config::Actions::SimpleGenerate, RailsAdmin::Config::Actions::BulkGenerate, RailsAdmin::Config::Actions::SimpleExpand, RailsAdmin::Config::Actions::BulkExpand, RailsAdmin::Config::Actions::Records, RailsAdmin::Config::Actions::SwitchScheduler, RailsAdmin::Config::Actions::SimpleExport, RailsAdmin::Config::Actions::Schedule, RailsAdmin::Config::Actions::Submit, RailsAdmin::Config::Actions::DeleteCollection].each { |a| RailsAdmin::Config::Actions.register(a) } RailsAdmin::Config::Actions.register(:export, RailsAdmin::Config::Actions::BulkExport) RailsAdmin::Config::Fields::Types.register(RailsAdmin::Config::Fields::Types::JsonValue) RailsAdmin::Config::Fields::Types.register(RailsAdmin::Config::Fields::Types::JsonSchema) RailsAdmin::Config::Fields::Types.register(RailsAdmin::Config::Fields::Types::StorageFile) { config: { mode: 'css', theme: 'neo', }, assets: { mode: '/assets/codemirror/modes/css.js', theme: '/assets/codemirror/themes/neo.css', } }.each { |option, configuration| RailsAdmin::Config::Fields::Types::CodeMirror.register_instance_option(option) { configuration } } RailsAdmin.config do |config| ## == PaperTrail == # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration config.authenticate_with do warden.authenticate! scope: :user end config.current_user_method { current_user } config.audit_with :mongoid_audit config.authorize_with :cancan config.excluded_models += [Setup::BaseOauthAuthorization, Setup::AwsAuthorization] config.actions do dashboard # mandatory # memory_usage # disk_usage index # mandatory new { except [Setup::Event, Setup::DataType, Setup::Authorization, Setup::BaseOauthProvider] } import import_schema translator_update convert export bulk_delete show run edit simple_share bulk_share build_gem pull upload_file download_file load_model shutdown_model process_flow authorize simple_generate bulk_generate simple_expand bulk_expand records switch_navigation switch_scheduler simple_export schedule retry_task submit simple_delete_data_type bulk_delete_data_type delete delete_library delete_collection #show_in_app send_to_flow delete_all data_type # history_index do # only [Setup::DataType, Setup::Webhook, Setup::Flow, Setup::Schema, Setup::Event, Setup::Connection, Setup::ConnectionRole, Setup::Library] # end # history_show do # only [Setup::DataType, Setup::Webhook, Setup::Flow, Setup::Schema, Setup::Event, Setup::Connection, Setup::ConnectionRole, Setup::Notification, Setup::Library] # end end config.model Setup::Validator do visible false end config.model Setup::Library do navigation_label 'Data Definitions' weight -16 configure :name do read_only { !bindings[:object].new_record? } help '' end edit do field :name field :slug end show do field :name field :slug field :schemas field :data_types field :_id field :created_at #field :creator field :updated_at #field :updater end fields :name, :slug, :schemas, :data_types end config.model Setup::Schema do object_label_method { :custom_title } navigation_label 'Data Definitions' weight -18 edit do field :library do read_only { !bindings[:object].new_record? } inline_edit false end field :uri do read_only { !bindings[:object].new_record? } html_attributes do { cols: '74', rows: '1' } end end field :schema, :code_mirror do html_attributes do { cols: '74', rows: '15' } end end field :schema_data_type do inline_edit false inline_add false end end show do field :library field :uri field :schema do pretty_value do pretty_value = if json = JSON.parse(value) rescue nil "<code class='json'>#{JSON.pretty_generate(json)}</code>" elsif xml = Nokogiri::XML(value) rescue nil "<code class='xml'>#{xml.to_xml}</code>" else value end "<pre>#{pretty_value}</pre>".html_safe end end field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :library, :uri, :schema_data_type end config.model Setup::DataType do label 'Data type' label_plural 'Data types' object_label_method { :custom_title } navigation_label 'Data Definitions' weight -17 group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :slug configure :storage_size, :decimal do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = bindings[:controller].instance_variable_get(:@objects).collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :title field :before_save_callbacks field :records_methods field :data_type_methods end list do field :title field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::DataType.fields[:used_memory.to_s].type.new(Setup::DataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::DataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size end show do field :title field :name field :slug field :activated field :schema do pretty_value do pretty_value = if json = JSON.pretty_generate(value) rescue nil "<code class='json'>#{json}</code>" else value end "<pre>#{pretty_value}</pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end fields :title, :name, :used_memory end config.model Setup::EdiValidator do object_label_method { :custom_title } label 'EDI Validators' navigation_label 'Data Definitions' fields :namespace, :name, :schema_data_type, :content_type end config.model Setup::AlgorithmValidator do object_label_method { :custom_title } navigation_label 'Data Definitions' fields :namespace, :name, :algorithm end config.model Setup::FileDataType do object_label_method { :custom_title } group :content do label 'Content' end group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :library do associated_collection_scope do library = (obj = bindings[:object]).library Proc.new { |scope| if library scope.where(id: library.id) else scope end } end end configure :used_memory do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::SchemaDataType.fields[:used_memory.to_s].type.new(Setup::SchemaDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::SchemaDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end configure :storage_size, :decimal do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = bindings[:controller].instance_variable_get(:@objects).collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe end read_only true end configure :validators do group :content inline_add false end configure :schema_data_type do group :content inline_add false inline_edit false end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :library field :title field :name field :slug field :validators field :schema_data_type field :before_save_callbacks field :records_methods field :data_type_methods end list do field :title field :name field :slug field :validators field :schema_data_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::SchemaDataType.fields[:used_memory.to_s].type.new(Setup::SchemaDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::SchemaDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size end show do field :title field :name field :slug field :activated field :validators field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end end config.model Setup::SchemaDataType do group :behavior do label 'Behavior' active false end object_label_method { :custom_title } navigation_label 'Data Definitions' weight -17 register_instance_option(:after_form_partials) do %w(shutdown_and_reload) end configure :title configure :name do read_only { !bindings[:object].new_record? } end configure :schema, :code_mirror do html_attributes do report = bindings[:object].shutdown(report_only: true) reload = (report[:reloaded].collect(&:data_type) + report[:destroyed].collect(&:data_type)).uniq bindings[:object].instance_variable_set(:@_to_reload, reload) { cols: '74', rows: '15' } end # pretty_value do # "<pre><code class='json'>#{JSON.pretty_generate(value)}</code></pre>".html_safe # end end configure :storage_size, :decimal do pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = bindings[:controller].instance_variable_get(:@objects).collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe end end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :library field :title field :name field :slug field :schema, :json_schema do help { 'Required' } end field :before_save_callbacks field :records_methods field :data_type_methods end list do field :library field :title field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::SchemaDataType.fields[:used_memory.to_s].type.new(Setup::SchemaDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::SchemaDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size end show do field :library field :title field :name field :slug field :activated field :schema do pretty_value do "<pre><code class='ruby'>#{JSON.pretty_generate(value)}</code></pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end end config.model Setup::Connection do object_label_method { :custom_title } weight -15 group :credentials do label 'Credentials' end configure :key, :string do visible { bindings[:view]._current_user.has_role? :admin } html_attributes do { maxlength: 30, size: 30 } end group :credentials end configure :token, :text do visible { bindings[:view]._current_user.has_role? :admin } html_attributes do { cols: '50', rows: '1' } end group :credentials end configure :authorization do group :credentials inline_edit false visible { bindings[:view]._current_user.has_role? :admin } end configure :authorization_handler do group :credentials visible { bindings[:view]._current_user.has_role? :admin } end group :parameters do label 'Parameters & Headers' end configure :parameters do group :parameters visible { bindings[:view]._current_user.has_role? :admin } end configure :headers do group :parameters visible { bindings[:view]._current_user.has_role? :admin } end configure :template_parameters do group :parameters visible { bindings[:view]._current_user.has_role? :admin } end show do field :namespace field :name field :url field :key field :token field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :url, :key, :token, :authorization, :authorization_handler, :parameters, :headers, :template_parameters end config.model Setup::Parameter do object_label_method { :to_s } edit do field :key field :value field :description field :metadata, :json_value end end config.model Setup::ConnectionRole do object_label_method { :custom_title } weight -14 configure :name, :string do help 'Requiered.' html_attributes do { maxlength: 50, size: 50 } end end configure :webhooks do nested_form false end configure :connections do nested_form false end modal do field :namespace field :name field :webhooks field :connections end show do field :namespace field :name field :webhooks field :connections field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :webhooks, :connections end config.model Setup::Webhook do object_label_method { :custom_title } weight -13 configure :metadata, :json_value group :credentials do label 'Credentials' end configure :authorization do group :credentials inline_edit false visible { bindings[:view]._current_user.has_role? :admin } end configure :authorization_handler do group :credentials visible { bindings[:view]._current_user.has_role? :admin } end group :parameters do label 'Parameters & Headers' end configure :path, :string do help 'Requiered. Path of the webhook relative to connection URL.' html_attributes do { maxlength: 255, size: 100 } end end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end show do field :namespace field :name field :path field :method field :description field :metadata, :json_value field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :path, :method, :description, :metadata, :authorization, :authorization_handler, :parameters, :headers, :template_parameters end config.model Setup::Task do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::FlowExecution do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :flow, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::DataTypeGeneration do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::DataTypeExpansion do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Translation do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::DataImport do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end fields :translator, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::SchemasImport do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :library, :base_uri, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Deletion do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :deletion_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.contextualized_label(:menu), v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end edit do field :description end fields :deletion_model, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::AlgorithmExecution do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :algorithm, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Submission do navigation_label 'Monitor' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :webhook, :connection, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end config.model Setup::Notification do navigation_label 'Monitor' object_label_method { :label } configure :created_at configure :type do pretty_value do color = case bindings[:object].type when :info 'green' when :notice 'blue' when :warning 'orange' else 'red' end "<label style='color:#{color}'>#{value.to_s.capitalize}</label>".html_safe end end configure :message do pretty_value do color = case bindings[:object].type when :info 'green' when :notice 'blue' when :warning 'orange' else 'red' end "<label style='color:#{color}'>#{value}</label>".html_safe end end configure :attachment, :storage_file fields :created_at, :type, :message, :attachment, :task end config.model Setup::Flow do object_label_method { :custom_title } register_instance_option(:form_synchronized) do [:custom_data_type, :data_type_scope, :scope_filter, :scope_evaluator, :lot_size, :connection_role, :webhook, :response_translator, :response_data_type] end edit do field :namespace field :name field :event do inline_edit false inline_add false end field :translator do help 'Required' end field :custom_data_type do inline_edit false inline_add false visible do if (f = bindings[:object]).custom_data_type.present? f.nil_data_type = false end if f.translator.present? && f.translator.data_type.nil? && !f.nil_data_type f.instance_variable_set(:@selecting_data_type, f.custom_data_type = f.event && f.event.try(:data_type)) unless f.data_type f.nil_data_type = f.translator.type == :Export && (params = (controller = bindings[:controller]).params) && (params = params[controller.abstract_model.param_key]) && params[:custom_data_type_id].blank? && params.keys.include?(:custom_data_type_id.to_s) true else false end end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) 'Source data type' else 'Target data type' end else 'Data type' end end help do if bindings[:object].nil_data_type '' elsif (translator = bindings[:object].translator) && [:Export, :Conversion].include?(translator.type) 'Optional' else 'Required' end end end field :nil_data_type do visible { bindings[:object].nil_data_type } label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) 'No source data type' else 'No target data type' end else 'No data type' end end end field :data_type_scope do visible do bindings[:controller].instance_variable_set(:@_data_type, bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'translator_id') (f = bindings[:object]).translator.present? && f.translator.type != :Import && f.data_type && !f.instance_variable_get(:@selecting_data_type) end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) 'Source scope' else 'Target scope' end else 'Data type scope' end end help 'Required' end field :scope_filter do visible { bindings[:object].scope_symbol == :filtered } partial 'form_triggers' help false end field :scope_evaluator do inline_add false inline_edit false visible { bindings[:object].scope_symbol == :evaluation } associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end help 'Required' end field :lot_size do visible { (f = bindings[:object]).translator.present? && f.translator.type == :Export && !f.nil_data_type && f.data_type_scope && f.scope_symbol != :event_source } end field :webhook do visible { (translator = (f = bindings[:object]).translator) && (translator.type == :Import || (translator.type == :Export && (bindings[:object].data_type_scope.present? || f.nil_data_type))) } help 'Required' end field :connection_role do visible { (translator = (f = bindings[:object]).translator) && (translator.type == :Import || (translator.type == :Export && (bindings[:object].data_type_scope.present? || f.nil_data_type))) } help 'Optional' end field :response_translator do visible { (translator = (f = bindings[:object]).translator) && (translator.type == :Export && (bindings[:object].data_type_scope.present? || f.nil_data_type)) && f.ready_to_save? } associated_collection_scope do Proc.new { |scope| scope.where(type: :Import) } end end field :response_data_type do inline_edit false inline_add false visible { (response_translator = bindings[:object].response_translator) && response_translator.type == :Import && response_translator.data_type.nil? } help '' end field :discard_events do visible { (((obj = bindings[:object]).translator && obj.translator.type == :Import) || obj.response_translator.present?) && obj.ready_to_save? } help "Events won't be fired for created or updated records if checked" end field :active do visible { bindings[:object].ready_to_save? } end field :notify_request do visible { (obj = bindings[:object]).translator && [:Import, :Export].include?(obj.translator.type) && obj.ready_to_save? } help 'Track request via notifications if checked' end field :notify_response do visible { (obj = bindings[:object]).translator && [:Import, :Export].include?(obj.translator.type) && obj.ready_to_save? } help 'Track responses via notification if checked' end field :after_process_callbacks do visible { bindings[:object].ready_to_save? } help 'Algorithms executed after flow processing, execution state is supplied as argument' end end show do field :namespace field :name field :active field :event field :translator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :active, :event, :translator end config.model Setup::Event do object_label_method { :custom_title } edit do field :namespace field :name end show do field :namespace field :name field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name end config.model Setup::Observer do object_label_method { :custom_title } edit do field :namespace field :name field :data_type do inline_add false inline_edit false associated_collection_scope do data_type = bindings[:object].data_type Proc.new { |scope| if data_type scope.where(id: data_type.id) else scope end } end help 'Required' end field :trigger_evaluator do visible { (obj = bindings[:object]).data_type.blank? || obj.trigger_evaluator.present? || obj.triggers.nil? } associated_collection_scope do Proc.new { |scope| scope.all.or(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :triggers do visible do bindings[:controller].instance_variable_set(:@_data_type, data_type = bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'data_type_id') data_type.present? && !bindings[:object].trigger_evaluator.present? end partial 'form_triggers' help false end end show do field :namespace field :name field :data_type field :triggers field :trigger_evaluator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :data_type, :triggers, :trigger_evaluator end config.model Setup::Scheduler do object_label_method { :custom_title } edit do field :namespace field :name field :scheduling_method field :expression do visible { bindings[:object].scheduling_method.present? } label do case bindings[:object].scheduling_method when :Once 'Date and time' when :Periodic 'Duration' when :CRON 'CRON Expression' else 'Expression' end end help do case bindings[:object].scheduling_method when :Once 'Select a date and a time' when :Periodic 'Type a time duration' when :CRON 'Type a CRON Expression' else 'Expression' end end partial { bindings[:object].scheduling_method == :Once ? 'form_datetime_wrapper' : 'form_text' } html_attributes do { rows: '1' } end end end show do field :namespace field :name field :expression field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :scheduling_method, :expression, :activated end config.model Setup::Translator do object_label_method { :custom_title } register_instance_option(:form_synchronized) do [:source_data_type, :target_data_type, :transformation, :target_importer, :source_exporter, :discard_chained_records] end edit do field :namespace field :name field :type field :source_data_type do inline_edit false inline_add false visible { [:Export, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :target_data_type do inline_edit false inline_add false visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :discard_events do visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help "Events won't be fired for created or updated records if checked" end field :style do visible { bindings[:object].type.present? } help 'Required' end field :bulk_source do visible { bindings[:object].type == :Export && bindings[:object].style.present? && bindings[:object].source_bulkable? } end field :mime_type do label 'MIME type' visible { bindings[:object].type == :Export && bindings[:object].style.present? } end field :file_extension do visible { bindings[:object].type == :Export && !bindings[:object].file_extension_enum.empty? } help { "Extensions for #{bindings[:object].mime_type}" } end field :source_handler do visible { (t = bindings[:object]).style.present? && (t.type == :Update || (t.type == :Conversion && t.style == 'ruby')) } help { 'Handle sources on transformation' } end field :transformation, :code_mirror do visible { bindings[:object].style.present? && bindings[:object].style != 'chain' } help { 'Required' } html_attributes do { cols: '74', rows: '15' } end end field :source_exporter do inline_add { bindings[:object].source_exporter.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type } help 'Required' associated_collection_scope do data_type = bindings[:object].source_data_type Proc.new { |scope| scope.all(type: :Conversion, source_data_type: data_type) } end end field :target_importer do inline_add { bindings[:object].target_importer.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help 'Required' associated_collection_scope do translator = bindings[:object] source_data_type = if translator.source_exporter translator.source_exporter.target_data_type else translator.source_data_type end target_data_type = bindings[:object].target_data_type Proc.new { |scope| scope = scope.all(type: :Conversion, source_data_type: source_data_type, target_data_type: target_data_type) } end end field :discard_chained_records do visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help "Chained records won't be saved if checked" end end show do field :namespace field :name field :type field :source_data_type field :bulk_source field :target_data_type field :discard_events field :style field :mime_type field :file_extension field :transformation do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :source_exporter field :target_importer field :discard_chained_records field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :type, :style, :transformation end config.model Setup::SharedName do visible { false } navigation_label 'Collections' fields :name, :owners end config.model Script do navigation_label 'Administration' configure :code, :code_mirror do help { 'Required' } pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end fields :name, :description, :code end config.model Setup::SharedCollection do register_instance_option(:discard_submit_buttons) do !(a = bindings[:action]) || a.key != :edit end navigation_label 'Collections' object_label_method { :versioned_name } weight -19 edit do field :image do visible { !bindings[:object].new_record? } end field :name do required { true } end field :shared_version do required { true } end field :authors field :summary field :description, :froala do end field :source_collection do visible { !((source_collection = bindings[:object].source_collection) && source_collection.new_record?) } inline_edit false inline_add false associated_collection_scope do source_collection = (obj = bindings[:object]).source_collection Proc.new { |scope| if obj.new_record? scope.where(id: source_collection ? source_collection.id : nil) else scope end } end end field :connections do inline_add false read_only do !bindings[:object].instance_variable_get(:@_selecting_connections) end help do nil end pretty_value do if bindings[:object].connections.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[connection_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No connection selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && obj.source_collection && obj.source_collection.connections.present? end associated_collection_scope do source_collection = bindings[:object].source_collection connections = (source_collection && source_collection.connections) || [] Proc.new { |scope| scope.any_in(id: connections.collect { |connection| connection.id }) } end end field :dependencies do inline_add false read_only do !bindings[:object].instance_variable_get(:@_selecting_dependencies) end help do nil end pretty_value do if bindings[:object].dependencies.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[dependency_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No dependencies selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) end end field :pull_parameters do visible do if !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && !obj.instance_variable_get(:@_selecting_connections) && (pull_parameters_enum = obj.enum_for_pull_parameters).present? bindings[:controller].instance_variable_set(:@shared_parameter_enum, pull_parameters_enum) true else false end end end end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :category field :summary field :description do pretty_value do value.html_safe end end field :authors field :dependencies field :_id field :created_at field :updated_at end list do field :image do thumb_method :icon end field :name do pretty_value do bindings[:object].versioned_name end end field :category field :authors field :summary field :dependencies end end config.model Setup::CollectionAuthor do object_label_method { :label } end config.model Setup::CollectionPullParameter do object_label_method { :label } field :label field :parameter, :enum do enum do bindings[:controller].instance_variable_get(:@shared_parameter_enum) || [bindings[:object].parameter] end end edit do field :label field :parameter end show do field :label field :parameter field :created_at #field :creator field :updated_at end fields :label, :parameter end config.model Setup::CollectionData do object_label_method { :label } end config.model Setup::Collection do navigation_label 'Collections' weight -19 group :setup do label 'Setup objects' active true end group :data do label 'Data' active false end configure :flows do group :setup end configure :connection_roles do group :setup end configure :translators do group :setup end configure :events do group :setup end configure :libraries do group :setup end configure :custom_validators do group :setup end configure :algorithms do group :setup end configure :webhooks do group :setup end configure :connections do group :setup end configure :authorizations do group :setup end configure :oauth_providers do group :setup end configure :oauth_clients do group :setup end configure :oauth2_scopes do group :setup end configure :data do group :data end show do field :image field :name field :flows field :connection_roles field :translators field :events field :libraries field :custom_validators field :algorithms field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :image do thumb_method :icon end field :name field :flows field :connection_roles field :translators field :events field :libraries field :custom_validators field :algorithms field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data end end config.model Setup::CustomValidator do visible false end config.model Setup::Integration do edit do field :name field :pull_connection field :pull_event do inline_add { false } inline_edit { false } end field :data_type field :receiver_connection end show do field :name field :pull_connection field :pull_flow field :pull_event field :pull_translator field :data_type field :send_translator field :send_flow field :receiver_connection end fields :name, :pull_connection, :pull_flow, :pull_event, :pull_translator, :data_type, :send_translator, :send_flow, :receiver_connection end config.model Setup::Algorithm do object_label_method { :custom_title } edit do field :namespace field :name field :description field :parameters field :code, :code_mirror do help { 'Required' } end field :call_links do visible { bindings[:object].call_links.present? } end end show do field :namespace field :name field :description field :parameters field :code do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :_id end fields :namespace, :name, :description, :parameters, :call_links end config.model Setup::CallLink do edit do field :name do read_only true help { nil } label 'Call name' end field :link do inline_add false inline_edit false help { nil } end end fields :name, :link end config.model Role do navigation_label 'Administration' fields :name, :users end config.model User do navigation_label 'Administration' object_label_method { :label } group :credentials do label 'Credentials' active true end group :activity do label 'Activity' active true end configure :name configure :email configure :roles configure :account do read_only { true } end configure :password do group :credentials end configure :password_confirmation do group :credentials end configure :key do group :credentials end configure :authentication_token do group :credentials end configure :confirmed_at do group :activity end configure :sign_in_count do group :activity end configure :current_sign_in_at do group :activity end configure :last_sign_in_at do group :activity end configure :current_sign_in_ip do group :activity end configure :last_sign_in_ip do group :activity end edit do field :picture field :name field :email do visible { Account.current.super_admin? } end field :roles do visible { Account.current.super_admin? } end field :account do label { Account.current.super_admin? ? 'Account' : 'Account settings' } help { nil } end field :password do visible { Account.current.super_admin? } end field :password_confirmation do visible { Account.current.super_admin? } end field :key do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :authentication_token do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :confirmed_at do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :sign_in_count do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :current_sign_in_at do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :last_sign_in_at do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :current_sign_in_ip do visible { !bindings[:object].new_record? && Account.current.super_admin? } end field :last_sign_in_ip do visible { !bindings[:object].new_record? && Account.current.super_admin? } end end show do field :picture field :name field :email field :account field :roles field :key field :authentication_token field :sign_in_count field :current_sign_in_at field :last_sign_in_at field :current_sign_in_ip field :last_sign_in_ip end fields :picture, :name, :email, :account, :roles, :key, :authentication_token, :authentication_token, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip end config.model Account do navigation_label 'Administration' object_label_method { :label } configure :_id do visible { Account.current.super_admin? } end configure :name do visible { Account.current.super_admin? } end configure :owner do read_only { !Account.current.super_admin? } help { nil } end configure :tenant_account do visible { Account.current.super_admin? } end configure :number do visible { Account.current.super_admin? } end configure :users do visible { Account.current.super_admin? } end configure :notification_level fields :_id, :name, :owner, :tenant_account, :number, :users, :notification_level end config.model Setup::SharedName do navigation_label 'Administration' fields :name, :owners end config.model Script do navigation_label 'Administration' edit do field :name field :description field :code, :code_mirror end show do field :name field :description field :code do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end end fields :name, :description, :code end config.model CenitToken do navigation_label 'Administration' end config.model Setup::BaseOauthProvider do object_label_method { :custom_title } label 'Provider' navigation_label 'OAuth' configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :parameters, :clients, :tenant, :shared end config.model Setup::OauthProvider do object_label_method { :custom_title } configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :request_token_endpoint, :parameters, :tenant, :shared end config.model Setup::Oauth2Provider do object_label_method { :custom_title } configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :parameters, :scope_separator, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :shared end config.model Setup::OauthParameter do navigation_label 'OAuth' object_label_method { :to_s } fields :key, :value end config.model Setup::OauthClient do object_label_method { :custom_title } navigation_label 'OAuth' configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end configure :identifier do pretty_value do if Account.current.super_admin? || Account.current.users.collect(&:id).include?(bindings[:object].creator_id) value else '<i class="icon-lock"/>'.html_safe end end end configure :secret do pretty_value do if Account.current.super_admin? || Account.current.users.collect(&:id).include?(bindings[:object].creator_id) value else '<i class="icon-lock"/>'.html_safe end end end fields :namespace, :name, :provider, :identifier, :secret, :tenant, :shared end config.model Setup::Oauth2Scope do object_label_method { :custom_title } navigation_label 'OAuth' configure :tenant do visible { Account.current.super_admin? } read_only { true } help '' end configure :shared do visible { Account.current.super_admin? } end fields :provider, :name, :description, :tenant, :shared end config.model Setup::Authorization do fields :namespace, :name end config.model Setup::OauthAuthorization do parent Setup::Authorization edit do field :namespace field :name field :provider do inline_add false inline_edit false associated_collection_scope do provider = (obj = bindings[:object]) && obj.provider Proc.new { |scope| if provider scope.any_in(id: provider.id) else scope.any_in(_type: Setup::OauthProvider.to_s) end } end end field :client do inline_add false inline_edit false visible do if ((obj = bindings[:object]) && obj.provider).present? obj.client = obj.provider.clients.first if obj.client.blank? true else false end end associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :access_token_secret do group :credentials end configure :realm do group :credentials end show do field :namespace field :name field :provider field :client field :access_token field :access_token_secret field :realm field :token_span field :authorized_at end fields :namespace, :name, :provider, :client end config.model Setup::Oauth2Authorization do parent Setup::Authorization edit do field :namespace field :name field :provider do inline_add false inline_edit false associated_collection_scope do provider = (obj = bindings[:object]) && obj.provider Proc.new { |scope| if provider scope.any_in(id: provider.id) else scope.any_in(_type: Setup::Oauth2Provider.to_s) end } end end field :client do inline_add false inline_edit false visible do if ((obj = bindings[:object]) && obj.provider).present? obj.client = obj.provider.clients.first if obj.client.blank? true else false end end associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end field :scopes do visible { ((obj = bindings[:object]) && obj.provider).present? } associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :refresh_token do group :credentials end configure :token_type do group :credentials end show do field :namespace field :name field :provider field :client field :scopes field :token_type field :access_token field :token_span field :authorized_at field :refresh_token end fields :namespace, :name, :provider, :client, :scopes end config.model Setup::AwsAuthorization do edit do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version end group :credentials do label 'Credentials' end configure :aws_access_key do group :credentials end configure :aws_secret_key do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version end fields :namespace, :name, :aws_access_key, :aws_secret_key, :seller, :merchant, :markets, :signature_method, :signature_version end config.model Setup::BasicAuthorization do edit do field :namespace field :name field :username field :password end group :credentials do label 'Credentials' end configure :username do group :credentials end configure :password do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version end fields :namespace, :name, :username, :password end config.model Setup::Raml do configure :raml_references do visible { bindings[:view]._current_user.has_role? :admin } end show do field :api_name field :api_version field :repo field :raml_doc field :raml_references end edit do field :api_name field :api_version field :repo field :raml_doc field :raml_references end fields :api_name, :api_version, :repo, :raml_doc, :raml_references end config.model Setup::RamlReference do object_label_method { :to_s } edit do field :path field :content end fields :path, :content end config.model Setup::Storage do object_label_method { :label } configure :filename do label 'File name' pretty_value { bindings[:object].storage_name } end configure :length do label 'Size' pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_length) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.max) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end configure :storer_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.label, v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end configure :storer_object do label 'Object' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value.class) am = amc.abstract_model wording = value.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, value)) (can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: value.id), class: 'pjax') : wording).html_safe end end end configure :storer_property do label 'Property' end fields :storer_model, :storer_object, :storer_property, :filename, :contentType, :length end config.model Setup::DelayedMessage do navigation_label 'Administration' end config.model Setup::SystemNotification do navigation_label 'Administration' end end
require 'account' [ RailsAdmin::Config::Actions::DiskUsage, RailsAdmin::Config::Actions::SendToFlow, RailsAdmin::Config::Actions::SwitchNavigation, RailsAdmin::Config::Actions::DataType, RailsAdmin::Config::Actions::Import, #RailsAdmin::Config::Actions::EdiExport, RailsAdmin::Config::Actions::ImportSchema, RailsAdmin::Config::Actions::DeleteAll, RailsAdmin::Config::Actions::TranslatorUpdate, RailsAdmin::Config::Actions::Convert, RailsAdmin::Config::Actions::SimpleShare, RailsAdmin::Config::Actions::BulkShare, RailsAdmin::Config::Actions::Pull, RailsAdmin::Config::Actions::RetryTask, RailsAdmin::Config::Actions::DownloadFile, RailsAdmin::Config::Actions::ProcessFlow, RailsAdmin::Config::Actions::BuildGem, RailsAdmin::Config::Actions::Run, RailsAdmin::Config::Actions::Authorize, RailsAdmin::Config::Actions::SimpleDeleteDataType, RailsAdmin::Config::Actions::BulkDeleteDataType, RailsAdmin::Config::Actions::SimpleGenerate, RailsAdmin::Config::Actions::BulkGenerate, RailsAdmin::Config::Actions::SimpleExpand, RailsAdmin::Config::Actions::BulkExpand, RailsAdmin::Config::Actions::Records, RailsAdmin::Config::Actions::SwitchScheduler, RailsAdmin::Config::Actions::SimpleExport, RailsAdmin::Config::Actions::Schedule, RailsAdmin::Config::Actions::Submit, RailsAdmin::Config::Actions::Trash, RailsAdmin::Config::Actions::Inspect, RailsAdmin::Config::Actions::Copy, RailsAdmin::Config::Actions::Cancel, RailsAdmin::Config::Actions::Configure, RailsAdmin::Config::Actions::SimpleCrossShare, RailsAdmin::Config::Actions::BulkCrossShare, RailsAdmin::Config::Actions::Regist, RailsAdmin::Config::Actions::SharedCollectionIndex, RailsAdmin::Config::Actions::BulkPull, RailsAdmin::Config::Actions::CleanUp, RailsAdmin::Config::Actions::ShowRecords, RailsAdmin::Config::Actions::RunScript, RailsAdmin::Config::Actions::Play, RailsAdmin::Config::Actions::PullImport, RailsAdmin::Config::Actions::State, RailsAdmin::Config::Actions::Documentation, RailsAdmin::Config::Actions::Push ].each { |a| RailsAdmin::Config::Actions.register(a) } RailsAdmin::Config::Actions.register(:export, RailsAdmin::Config::Actions::BulkExport) [ RailsAdmin::Config::Fields::Types::JsonValue, RailsAdmin::Config::Fields::Types::JsonSchema, RailsAdmin::Config::Fields::Types::StorageFile, RailsAdmin::Config::Fields::Types::EnumEdit, RailsAdmin::Config::Fields::Types::Model, RailsAdmin::Config::Fields::Types::Record, RailsAdmin::Config::Fields::Types::HtmlErb, RailsAdmin::Config::Fields::Types::OptionalBelongsTo, RailsAdmin::Config::Fields::Types::Code ].each { |f| RailsAdmin::Config::Fields::Types.register(f) } module RailsAdmin module Config class << self def navigation(label, options) navigation_options[label.to_s] = options end def navigation_options @nav_options ||= {} end end end end RailsAdmin.config do |config| config.total_columns_width = 900 ## == PaperTrail == # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration config.authenticate_with do warden.authenticate! scope: :user unless %w(dashboard shared_collection_index index show).include?(action_name) end config.current_user_method { current_user } config.audit_with :mongoid_audit config.authorize_with :cancan config.excluded_models += [Setup::BaseOauthAuthorization, Setup::AwsAuthorization] config.actions do dashboard # mandatory # disk_usage shared_collection_index index # mandatory new { except [Setup::Event, Setup::DataType, Setup::Authorization, Setup::BaseOauthProvider] } import import_schema pull_import translator_update convert export bulk_delete show show_records run run_script edit configure play copy simple_share bulk_share simple_cross_share bulk_cross_share build_gem pull bulk_pull push download_file process_flow authorize simple_generate bulk_generate simple_expand bulk_expand records switch_navigation switch_scheduler simple_export schedule state retry_task submit inspect cancel regist simple_delete_data_type bulk_delete_data_type delete trash clean_up #show_in_app send_to_flow delete_all data_type #history_index history_show do only do [ Setup::Algorithm, Setup::Connection, Setup::Webhook, Setup::Translator, Setup::Flow, Setup::OauthClient, Setup::Oauth2Scope ] + Setup::DataType.class_hierarchy + Setup::Validator.class_hierarchy + Setup::BaseOauthProvider.class_hierarchy end visible { only.include?((obj = bindings[:object]).class) && obj.try(:shared?) } end documentation end def shared_read_only instance_eval do read_only { (obj = bindings[:object]).creator_id != User.current.id && obj.shared? } end end shared_non_editable = Proc.new do shared_read_only end #Collections config.navigation 'Collections', icon: 'fa fa-cubes' config.model Setup::Tag do visible false object_label_method { :name } fields :namespace, :name end config.model Setup::CrossCollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CrossCollectionPullParameter do visible false object_label_method { :label } configure :location, :json_value edit do field :label field :property_name field :location end show do field :label field :property_name field :location field :created_at #field :creator field :updated_at end fields :label, :property_name, :location end config.model Setup::CrossSharedCollection do weight 000 label 'Cross Shared Collection' navigation_label 'Collections' object_label_method :versioned_name visible { Account.current_super_admin? } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' configure :readme, :html_erb configure :pull_data, :json_value configure :data, :json_value configure :swagger_spec, :json_value group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :title field :image field :logo_background, :color field :name field :shared_version field :summary field :category field :authors field :pull_count field :pull_parameters field :dependencies field :readme end show do field :title field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary field :readme field :authors field :pull_count field :_id field :updated_at field :data_schemas do label 'Schemas' group :data end field :data_custom_validators do label 'Validators' group :data end field :data_data_types do label 'Data Types' group :data end field :data_connections do label 'Connections' group :api_connectors end field :data_webhooks do label 'Webhooks' group :api_connectors end field :data_connection_roles do label 'Connection Roles' group :api_connectors end field :data_flows do label 'Flows' group :workflows end field :data_events do label 'Events' group :workflows end field :data_translators do label 'Translators' group :workflows end field :data_algorithms do label 'Algorithms' group :workflows end field :data_applications do label 'Applications' group :workflows end field :data_authorizations do label 'Autorizations' group :security end field :data_oauth_clients do label 'OAuth Clients' group :security end field :data_oauth_providers do label 'OAuth Providers' group :security end field :data_oauth2_scopes do label 'OAuth 2.0 Scopes' group :security end field :data_namespaces do label 'Namespaces' group :config end end end config.model Setup::SharedCollection do weight 010 label 'Shared Collection' register_instance_option(:discard_submit_buttons) do !(a = bindings[:action]) || a.key != :edit end navigation_label 'Collections' object_label_method { :versioned_name } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' group :collections group :workflows group :api_connectors do label 'Connectors' active true end group :data group :security edit do field :image do visible { !bindings[:object].instance_variable_get(:@sharing) } end field :logo_background field :name do required { true } end field :shared_version do required { true } end field :authors field :summary field :source_collection do visible { !((source_collection = bindings[:object].source_collection) && source_collection.new_record?) } inline_edit false inline_add false associated_collection_scope do source_collection = (obj = bindings[:object]).source_collection Proc.new { |scope| if obj.new_record? scope.where(id: source_collection ? source_collection.id : nil) else scope end } end end field :connections do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_connections)).nil? || v) end help do nil end pretty_value do if bindings[:object].connections.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[connection_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No connection selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && obj.source_collection && obj.source_collection.connections.present? end associated_collection_scope do source_collection = bindings[:object].source_collection connections = (source_collection && source_collection.connections) || [] Proc.new { |scope| scope.any_in(id: connections.collect { |connection| connection.id }) } end end field :dependencies do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_dependencies)).nil? || v) end help do nil end pretty_value do if bindings[:object].dependencies.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[dependency_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No dependencies selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) end end field :pull_parameters field :pull_count do visible { Account.current_super_admin? } end field :readme do visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && !obj.instance_variable_get(:@_selecting_connections) end end end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary do pretty_value do value.html_safe end end field :readme, :html_erb field :authors field :dependencies field :pull_count field :data_namespaces do group :collections label 'Namespaces' list_fields do %w(name slug) end end field :data_flows do group :workflows label 'Flows' list_fields do %w(namespace name) #TODO Inlude a description field on Flow model end end field :data_translators do group :workflows label 'Translators' list_fields do %w(namespace name type style) end end field :data_events do group :workflows label 'Events' list_fields do %w(namespace name _type) end end field :data_algorithms do group :workflows label 'Algorithms' list_fields do %w(namespace name description) end end field :data_connection_roles do group :api_connectors label 'Connection roles' list_fields do %w(namespace name) end end field :data_webhooks do group :api_connectors label 'Webhooks' list_fields do %w(namespace name path method description) end end field :data_connections do group :api_connectors label 'Connections' list_fields do %w(namespace name url) end end field :data_data_types do group :data label 'Data types' list_fields do %w(title name slug _type) end end field :data_schemas do group :data label 'Schemas' list_fields do %w(namespace uri) end end field :data_custom_validators do group :data label 'Custom validators' list_fields do %w(namespace name _type) #TODO Include a description field for Custom Validator model end end # field :data_data TODO Include collection data field field :data_authorizations do group :security label 'Authorizations' list_fields do %w(namespace name _type) end end field :data_oauth_providers do group :security label 'OAuth providers' list_fields do %w(namespace name response_type authorization_endpoint token_endpoint token_method _type) end end field :data_oauth_clients do group :security label 'OAuth clients' list_fields do %w(provider name) end end field :data_oauth2_scopes do group :security label 'OAuth 2.0 scopes' list_fields do %w(provider name description) end end field :_id field :updated_at end list do field :image do thumb_method :icon end field :name do pretty_value do bindings[:object].versioned_name end end field :authors field :summary field :pull_count field :dependencies end end config.model Setup::CollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CollectionPullParameter do visible false object_label_method { :label } field :label field :parameter, :enum do enum do bindings[:controller].instance_variable_get(:@shared_parameter_enum) || [bindings[:object].parameter] end end edit do field :label field :parameter field :property_name field :location, :json_value end show do field :label field :parameter field :created_at #field :creator field :updated_at end list do field :label field :parameter field :updated_at end fields :label, :parameter end config.model Setup::CollectionData do visible false object_label_method { :label } end config.model Setup::Collection do weight 020 navigation_label 'Collections' register_instance_option :label_navigation do 'My Collections' end group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :title field :image field :readme do visible { Account.current_super_admin? } end field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data end show do field :title field :image field :readme, :html_erb field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data field :namespaces field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :title field :image do thumb_method :icon end field :name field :flows do pretty_value do value.count > 0 ? value.count : '-' end end field :connection_roles do pretty_value do value.count > 0 ? value.count : '-' end end field :translators do pretty_value do value.count > 0 ? value.count : '-' end end field :events do pretty_value do value.count > 0 ? value.count : '-' end end field :data_types do pretty_value do value.count > 0 ? value.count : '-' end end field :schemas do pretty_value do value.count > 0 ? value.count : '-' end end field :custom_validators do pretty_value do value.count > 0 ? value.count : '-' end end field :algorithms do pretty_value do value.count > 0 ? value.count : '-' end end field :applications do pretty_value do value.count > 0 ? value.count : '-' end end field :webhooks do pretty_value do value.count > 0 ? value.count : '-' end end field :connections do pretty_value do value.count > 0 ? value.count : '-' end end field :authorizations do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_providers do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_clients do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth2_scopes do pretty_value do value.count > 0 ? value.count : '-' end end field :data field :updated_at end end #Definitions config.navigation 'Definitions', icon: 'fa fa-puzzle-piece' config.model Setup::Validator do navigation_label 'Definitions' label 'Validators' weight 100 fields :namespace, :name fields :namespace, :name, :updated_at show_in_dashboard false end config.model Setup::CustomValidator do visible false configure :_type do pretty_value do value.split('::').last.to_title end end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Schema do weight 101 object_label_method { :custom_title } edit do field :namespace, :enum_edit do read_only { !bindings[:object].new_record? } end field :uri do read_only { !bindings[:object].new_record? } html_attributes do { cols: '74', rows: '1' } end end field :schema, :code do html_attributes do { cols: '74', rows: '15' } end code_config do if bindings[:object].schema_type == :json_schema { mode: 'application/json' } else { mode: 'application/xml' } end end end field :schema_data_type do inline_edit false inline_add false end end show do field :namespace field :uri field :schema do pretty_value do v = if json = JSON.parse(value) rescue nil "<code class='json'>#{JSON.pretty_generate(json).gsub('<', '&lt;').gsub('>', '&gt;')}</code>" elsif (xml = Nokogiri::XML(value)).errors.blank? "<code class='xml'>#{xml.to_xml.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else "<code>#{value}</code>" end "<pre>#{v}</pre>".html_safe end end field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :uri, :schema_data_type, :updated_at end config.model Setup::XsltValidator do parent Setup::Validator weight 102 label 'XSLT Validator' object_label_method { :custom_title } list do field :namespace field :xslt field :updated_at end fields :namespace, :name, :xslt, :updated_at end config.model Setup::EdiValidator do parent Setup::Validator weight 103 object_label_method { :custom_title } label 'EDI Validator' edit do field :namespace, :enum_edit field :name field :schema_data_type field :content_type end fields :namespace, :name, :schema_data_type, :content_type, :updated_at end config.model Setup::AlgorithmValidator do parent Setup::Validator weight 104 label 'Algorithm Validator' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :algorithm end fields :namespace, :name, :algorithm, :updated_at end config.model Setup::DataType do navigation_label 'Definitions' weight 110 label 'Data Type' object_label_method { :custom_title } visible true show_in_dashboard false configure :_type do pretty_value do value.split('::').last.to_title end end group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :slug configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :title, :enum_edit, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::DataType.fields[:used_memory.to_s].type.new(Setup::DataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::DataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :name field :title field :slug field :_type field :storage_size field :schema do pretty_value do v = if json = JSON.pretty_generate(value) rescue nil "<code class='json'>#{json.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else value end "<pre>#{v}</pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :_type, :storage_size, :updated_at end config.model Setup::JsonDataType do navigation_label 'Definitions' weight 111 label 'JSON Data Type' object_label_method { :custom_title } group :behavior do label 'Behavior' active false end configure :title configure :name do read_only { !bindings[:object].new_record? } end configure :schema, :json_schema do html_attributes do { cols: '74', rows: '15' } end # pretty_value do # "<pre><code class='json'>#{JSON.pretty_generate(value)}</code></pre>".html_safe # end end configure :storage_size, :decimal do pretty_value do if (objects = bindings[:controller].instance_variable_get(:@objects)) unless (max = bindings[:controller].instance_variable_get(:@max_storage_size)) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :schema, :json_schema do shared_read_only help { 'Required' } end field :title, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless (max = bindings[:controller].instance_variable_get(:@max_used_memory)) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :title field :name field :slug field :storage_size field :schema do pretty_value do "<pre><code class='ruby'>#{JSON.pretty_generate(value)}</code></pre>".html_safe end end field :before_save_callbacks field :records_methods field :data_type_methods field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end config.model Setup::FileDataType do navigation_label 'Definitions' weight 112 label 'File Data Type' object_label_method { :custom_title } group :content do label 'Content' end group :behavior do label 'Behavior' active false end configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :validators do group :content inline_add false end configure :schema_data_type do group :content inline_add false inline_edit false end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :title, &shared_non_editable field :slug field :validators, &shared_non_editable field :schema_data_type, &shared_non_editable field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :validators field :schema_data_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :title field :name field :slug field :validators field :storage_size field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end #Connectors config.navigation 'Connectors', icon: 'fa fa-plug' config.model Setup::Parameter do visible false object_label_method { :to_s } configure :metadata, :json_value configure :value edit do field :name field :value field :description field :metadata end list do field :name field :value field :description field :metadata field :updated_at end end config.model Setup::Connection do navigation_label 'Connectors' weight 200 object_label_method { :custom_title } group :credentials do label 'Credentials' end configure :number, :string do label 'Key' html_attributes do { maxlength: 30, size: 30 } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :token, :text do html_attributes do { cols: '50', rows: '1' } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:url, &shared_non_editable) field :number field :token field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :url field :number field :token field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at field :updated_at end list do field :namespace field :name field :url field :number field :token field :authorization field :updated_at end fields :namespace, :name, :url, :number, :token, :authorization, :updated_at end config.model Setup::ConnectionRole do navigation_label 'Connectors' weight 210 label 'Connection Role' object_label_method { :custom_title } configure :name, :string do help 'Requiered.' html_attributes do { maxlength: 50, size: 50 } end end configure :webhooks do nested_form false end configure :connections do nested_form false end modal do field :namespace, :enum_edit field :name field :webhooks field :connections end show do field :namespace field :name field :webhooks field :connections field :_id field :created_at #field :creator field :updated_at #field :updater end edit do field :namespace, :enum_edit field :name field :webhooks field :connections end fields :namespace, :name, :webhooks, :connections, :updated_at end config.model Setup::Webhook do navigation_label 'Connectors' weight 220 object_label_method { :custom_title } configure :metadata, :json_value group :credentials do label 'Credentials' end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :path, :string do help 'Requiered. Path of the webhook relative to connection URL.' html_attributes do { maxlength: 255, size: 100 } end end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:path, &shared_non_editable) field(:method, &shared_non_editable) field(:description, &shared_non_editable) field(:metadata, :json_value, &shared_non_editable) field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :path field :method field :description field :metadata, :json_value field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :path, :method, :description, :authorization, :updated_at end #Security config.navigation 'Security', icon: 'fa fa-shield' config.model Setup::OauthClient do navigation_label 'Security' label 'OAuth Client' weight 300 object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :identifier do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :secret do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end fields :provider, :name, :identifier, :secret, :tenant, :updated_at end config.model Setup::BaseOauthProvider do navigation_label 'Security' weight 310 object_label_method { :custom_title } label 'Provider' configure :_type do pretty_value do value.split('::').last.to_title end end configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :namespace, :enum_edit list do field :namespace field :name field :_type field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :tenant field :updated_at end fields :namespace, :name, :_type, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :tenant end config.model Setup::OauthProvider do weight 311 label 'OAuth 1.0 provider' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit, &shared_non_editable field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :request_token_endpoint field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :request_token_endpoint, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Provider do weight 312 label 'OAuth 2.0 provider' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :scope_separator field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :scope_separator, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Scope do navigation_label 'Security' weight 320 label 'OAuth 2.0 Scope' object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end fields :provider, :name, :description, :tenant, :updated_at end config.model Setup::Authorization do navigation_label 'Security' weight 330 object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name field :metadata end fields :namespace, :name, :status, :_type, :metadata, :updated_at show_in_dashboard false end config.model Setup::BasicAuthorization do weight 331 register_instance_option :label_navigation do 'Basic' end object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value edit do field :namespace field :name field :username field :password field :metadata end group :credentials do label 'Credentials' end configure :username do group :credentials end configure :password do group :credentials end show do field :namespace field :name field :status field :username field :password field :metadata field :_id end edit do field :namespace, :enum_edit field :name field :username field :password end fields :namespace, :name, :status, :username, :password, :updated_at end config.model Setup::OauthAuthorization do weight 332 label 'OAuth 1.0 authorization' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace, :enum_edit field :name field :client field :parameters field :template_parameters field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :access_token_secret do group :credentials end configure :realm_id do group :credentials end show do field :namespace field :name field :status field :client field :parameters field :template_parameters field :metadata field :_id field :access_token field :access_token_secret field :realm_id field :token_span field :authorized_at end list do field :namespace field :name field :status field :client field :updated_at end fields :namespace, :name, :status, :client, :updated_at end config.model Setup::Oauth2Authorization do weight 333 label 'OAuth 2.0 authorization' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :expires_in do pretty_value do "#{value}s" if value end end edit do field :namespace, :enum_edit field :name field :client field :scopes do visible { bindings[:object].ready_to_save? } associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end field :parameters do visible { bindings[:object].ready_to_save? } end field :template_parameters do visible { bindings[:object].ready_to_save? } end field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :refresh_token do group :credentials end configure :token_type do group :credentials end show do field :namespace field :name field :status field :client field :scopes field :parameters field :template_parameters field :metadata field :_id field :expires_in field :id_token field :token_type field :access_token field :token_span field :authorized_at field :refresh_token field :_id end fields :namespace, :name, :status, :client, :scopes, :updated_at end config.model Setup::AwsAuthorization do weight -334 object_label_method { :custom_title } configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end group :credentials do label 'Credentials' end configure :aws_access_key do group :credentials end configure :aws_secret_key do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end list do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :updated_at end fields :namespace, :name, :aws_access_key, :aws_secret_key, :seller, :merchant, :markets, :signature_method, :signature_version, :updated_at end config.model Cenit::OauthAccessGrant do navigation_label 'Security' label 'Access Grants' weight 340 fields :created_at, :application_id, :scope end #Compute config.navigation 'Compute', icon: 'fa fa-cog' config.model Setup::AlgorithmParameter do visible false fields :name, :type, :many, :required, :default end config.model Setup::CallLink do visible false edit do field :name do read_only true help { nil } label 'Call name' end field :link do inline_add false inline_edit false help { nil } end end fields :name, :link end config.model Setup::Algorithm do navigation_label 'Compute' weight 400 object_label_method { :custom_title } extra_associations do association = Mongoid::Relations::Metadata.new( name: :stored_outputs, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::Algorithm.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end edit do field :namespace, :enum_edit field :name field :description field :parameters field :code, :code do html_attributes do { cols: '74', rows: '15' } end code_config do { mode: 'text/x-ruby' } end help { 'Required' } end field :call_links do visible { bindings[:object].call_links.present? } end field :store_output field :output_datatype field :validate_output end show do field :namespace field :name field :description field :parameters field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end field :call_links field :_id field :stored_outputs end list do field :namespace field :name field :description field :parameters field :call_links field :updated_at end fields :namespace, :name, :description, :parameters, :call_links end config.model Setup::Translator do navigation_label 'Compute' weight 410 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :source_data_type, :target_data_type, :transformation, :target_importer, :source_exporter, :discard_chained_records ] end end edit do field :namespace, :enum_edit field :name field :type field :source_data_type do inline_edit false inline_add false visible { [:Export, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :target_data_type do inline_edit false inline_add false visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :discard_events do visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help "Events won't be fired for created or updated records if checked" end field :style do visible { bindings[:object].type.present? } help 'Required' end field :bulk_source do visible { bindings[:object].type == :Export && bindings[:object].style.present? && bindings[:object].source_bulkable? } end field :mime_type do label 'MIME type' visible { bindings[:object].type == :Export && bindings[:object].style.present? } end field :file_extension do visible { bindings[:object].type == :Export && !bindings[:object].file_extension_enum.empty? } help { "Extensions for #{bindings[:object].mime_type}" } end field :source_handler do visible { (t = bindings[:object]).style.present? && (t.type == :Update || (t.type == :Conversion && t.style == 'ruby')) } help { 'Handle sources on transformation' } end field :transformation, :code do visible { bindings[:object].style.present? && bindings[:object].style != 'chain' } help { 'Required' } html_attributes do { cols: '74', rows: '15' } end code_config do { mode: case bindings[:object].style when 'html.erb' 'text/html' when 'xslt' 'application/xml' else 'text/x-ruby' end } end end field :source_exporter do inline_add { bindings[:object].source_exporter.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type } help 'Required' associated_collection_scope do data_type = bindings[:object].source_data_type Proc.new { |scope| scope.all(type: :Conversion, source_data_type: data_type) } end end field :target_importer do inline_add { bindings[:object].target_importer.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help 'Required' associated_collection_scope do translator = bindings[:object] source_data_type = if translator.source_exporter translator.source_exporter.target_data_type else translator.source_data_type end target_data_type = bindings[:object].target_data_type Proc.new { |scope| scope = scope.all(type: :Conversion, source_data_type: source_data_type, target_data_type: target_data_type) } end end field :discard_chained_records do visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help "Chained records won't be saved if checked" end end show do field :namespace field :name field :type field :source_data_type field :bulk_source field :target_data_type field :discard_events field :style field :mime_type field :file_extension field :transformation do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :source_exporter field :target_importer field :discard_chained_records field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :type field :style field :mime_type field :file_extension field :updated_at end fields :namespace, :name, :type, :style, :transformation, :updated_at end config.model Setup::AlgorithmOutput do navigation_label 'Compute' weight -405 visible false configure :records_count configure :input_parameters configure :created_at do label 'Recorded at' end extra_associations do association = Mongoid::Relations::Metadata.new( name: :records, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::AlgorithmOutput.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end show do field :created_at field :input_parameters field :records_count end fields :created_at, :input_parameters, :records_count end config.model Setup::Action do visible false navigation_label 'Compute' weight -402 object_label_method { :to_s } fields :method, :path, :algorithm end config.model Setup::Application do navigation_label 'Compute' weight 420 object_label_method { :custom_title } visible configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :slug field :actions field :application_parameters end list do field :namespace field :name field :slug field :registered field :actions field :application_parameters field :updated_at end fields :namespace, :name, :slug, :identifier, :secret_token, :registered, :actions, :application_parameters end config.model Cenit::ApplicationParameter do visible false navigation_label 'Compute' configure :group, :enum_edit list do field :name field :type field :many field :group field :description field :updated_at end fields :name, :type, :many, :group, :description end config.model Setup::Snippet do navigation_label 'Compute' weight 430 object_label_method { :custom_title } visible { Account.current_super_admin? } configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :type field :description field :code, :code do html_attributes do { cols: '74', rows: '15' } end help { 'Required' } code_config do { mode: { 'auto': 'javascript', 'text': 'javascript', 'null': 'javascript', 'c': 'clike', 'cpp': 'clike', 'csharp': 'clike', 'csv': 'javascript', 'fsharp': 'mllike', 'java': 'clike', 'latex': 'stex', 'ocaml': 'mllike', 'scala': 'clike', 'squirrel': 'clike' }[bindings[:object].type] || bindings[:object].type } end end field :tags end show do field :namespace, :enum_edit field :name field :type field :description field :code do pretty_value do "<pre><code class='#{bindings[:object].type}'>#{value}</code></pre>".html_safe end end field :tags end list do field :namespace field :name field :type field :tags end fields :namespace, :name, :type, :description, :code, :tags end #Workflows config.navigation 'Workflows', icon: 'fa fa-cogs' config.model Setup::Flow do navigation_label 'Workflows' weight 500 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :custom_data_type, :data_type_scope, :scope_filter, :scope_evaluator, :lot_size, :connection_role, :webhook, :response_translator, :response_data_type ] end end Setup::FlowConfig.config_fields.each do |f| configure f.to_sym, Setup::Flow.data_type.schema['properties'][f]['type'].to_sym end edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :event, :optional_belongs_to do inline_edit false inline_add false visible do (f = bindings[:object]).not_shared? || f.data_type_scope.present? end end field :translator do help I18n.t('admin.form.required') shared_read_only end field :custom_data_type, :optional_belongs_to do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] if (t = f.translator) && t.data_type.nil? unless f.data_type if f.custom_data_type_selected? f.custom_data_type = nil f.data_type_scope = nil else f.custom_data_type = f.event.try(:data_type) end end true else f.custom_data_type = nil false end end required do bindings[:object].event.present? end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_data_type') else I18n.t('admin.form.flow.target_data_type') end else I18n.t('admin.form.flow.data_type') end end end field :data_type_scope do shared_read_only visible do f = bindings[:object] #For filter scope bindings[:controller].instance_variable_set(:@_data_type, f.data_type) bindings[:controller].instance_variable_set(:@_update_field, 'translator_id') if f.shared? value.present? else f.event && (t = f.translator) && t.type != :Import && (f.custom_data_type_selected? || f.data_type) end end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_scope') else I18n.t('admin.form.flow.target_scope') end else I18n.t('admin.form.flow.data_type_scope') end end help I18n.t('admin.form.required') end field :scope_filter do shared_read_only visible do f = bindings[:object] f.scope_symbol == :filtered end partial 'form_triggers' help I18n.t('admin.form.required') end field :scope_evaluator do inline_add false inline_edit false shared_read_only visible do f = bindings[:object] f.scope_symbol == :evaluation end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end help I18n.t('admin.form.required') end field :lot_size do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.custom_data_type_selected? && (f.event.blank? || f.data_type.blank? || (f.data_type_scope.present? && f.scope_symbol != :event_source)) end end field :webhook do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end help I18n.t('admin.form.required') end field :authorization do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :connection_role do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :before_submit do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :response_translator do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.ready_to_save? end associated_collection_scope do Proc.new { |scope| scope.where(type: :Import) } end end field :response_data_type do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] (resp_t = f.response_translator) && resp_t.type == :Import && resp_t.data_type.nil? end help I18n.t('admin.form.required') end field :discard_events do visible do f = bindings[:object] ((f.translator && f.translator.type == :Import) || f.response_translator.present?) && f.ready_to_save? end help I18n.t('admin.form.flow.events_wont_be_fired') end field :active do visible do f = bindings[:object] f.ready_to_save? end end field :notify_request do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help I18n.t('admin.form.flow.notify_request') end field :notify_response do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help help I18n.t('admin.form.flow.notify_response') end field :after_process_callbacks do shared_read_only visible do bindings[:object].ready_to_save? end help I18n.t('admin.form.flow.after_process_callbacks') associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end end show do field :namespace field :name field :active field :event field :translator field :custom_data_type field :data_type_scope field :scope_filter field :scope_evaluator field :lot_size field :webhook field :authorization field :connection_role field :before_submit field :response_translator field :response_data_type field :discard_events field :notify_request field :notify_response field :after_process_callbacks field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :active field :event field :translator field :updated_at end fields :namespace, :name, :active, :event, :translator, :updated_at end config.model Setup::Event do navigation_label 'Workflows' weight 510 object_label_method { :custom_title } visible false configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name end show do field :namespace field :name field :_type field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Observer do navigation_label 'Workflows' weight 511 label 'Data Event' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :data_type do inline_add false inline_edit false associated_collection_scope do data_type = bindings[:object].data_type Proc.new { |scope| if data_type scope.where(id: data_type.id) else scope end } end help 'Required' end field :trigger_evaluator do visible { (obj = bindings[:object]).data_type.blank? || obj.trigger_evaluator.present? || obj.triggers.nil? } associated_collection_scope do Proc.new { |scope| scope.all.or(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :triggers do visible do bindings[:controller].instance_variable_set(:@_data_type, data_type = bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'data_type_id') data_type.present? && !bindings[:object].trigger_evaluator.present? end partial 'form_triggers' help false end end show do field :namespace field :name field :data_type field :triggers field :trigger_evaluator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :data_type, :triggers, :trigger_evaluator, :updated_at end config.model Setup::Scheduler do navigation_label 'Workflows' weight 512 object_label_method { :custom_title } configure :expression, :json_value edit do field :namespace, :enum_edit field :name field :expression do visible true label 'Scheduling type' help 'Configure scheduler' partial :scheduler html_attributes do { rows: '1' } end end end show do field :namespace field :name field :expression field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :expression field :activated field :updated_at end fields :namespace, :name, :expression, :activated, :updated_at end #Monitors config.navigation 'Monitors', icon: 'fa fa-heartbeat' config.model Setup::Notification do navigation_label 'Monitors' weight 600 object_label_method { :label } show_in_dashboard false configure :created_at configure :type do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value.to_s.capitalize}</label>".html_safe end end configure :message do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value}</label>".html_safe end end configure :attachment, :storage_file list do field :created_at do visible do if (account = Account.current) account.notifications_listed_at = Time.now end true end end field :type field :message field :attachment field :task field :updated_at end end config.model Setup::Task do navigation_label 'Monitors' weight 610 object_label_method { :to_s } show_in_dashboard false configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :updated_at end config.model Setup::FlowExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :flow, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeGeneration do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeExpansion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Translation do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Push do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :source_collection, :shared_collection, :description, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::BasePull do navigation_label 'Monitors' visible false label 'Pull' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::PullImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :data do label 'Pull data' end edit do field :description end fields :data, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SharedCollectionPull do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :shared_collection, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SchemasImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :base_uri, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Deletion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :deletion_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.contextualized_label(:menu), v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end edit do field :description end fields :deletion_model, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::AlgorithmExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :algorithm, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Submission do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :webhook, :connection, :authorization, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Storage do navigation_label 'Monitors' show_in_dashboard false weight 620 object_label_method { :label } configure :filename do label 'File name' pretty_value { bindings[:object].storage_name } end configure :length do label 'Size' pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_length) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.reject(&:nil?).max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end configure :storer_model, :model do label 'Model' end configure :storer_object, :record do label 'Object' end configure :storer_property do label 'Property' end list do field :storer_model field :storer_object field :storer_property field :filename field :contentType field :length field :updated_at end fields :storer_model, :storer_object, :storer_property, :filename, :contentType, :length end #Configuration config.navigation 'Configuration', icon: 'fa fa-sliders' config.model Setup::Namespace do navigation_label 'Configuration' weight 700 fields :name, :slug, :updated_at show_in_dashboard false end config.model Setup::DataTypeConfig do navigation_label 'Configuration' label 'Data Type Config' weight 710 configure :data_type do read_only true end fields :data_type, :slug, :navigation_link, :updated_at show_in_dashboard false end config.model Setup::FlowConfig do navigation_label 'Configuration' label 'Flow Config' weight 720 configure :flow do read_only true end fields :flow, :active, :notify_request, :notify_response, :discard_events show_in_dashboard false end config.model Setup::ConnectionConfig do navigation_label 'Configuration' label 'Connection Config' weight 730 configure :connection do read_only true end configure :number do label 'Key' end fields :connection, :number, :token show_in_dashboard false end config.model Setup::Pin do navigation_label 'Configuration' weight 740 object_label_method :to_s configure :model, :model configure :record, :record edit do field :record_model do label 'Model' help 'Required' end Setup::Pin.models.values.each do |m_data| field m_data[:property] do inline_add false inline_edit false help 'Required' visible { bindings[:object].record_model == m_data[:model_name] } associated_collection_scope do field = "#{m_data[:property]}_id".to_sym excluded_ids = Setup::Pin.where(field.exists => true).collect(&field) unless (pin = bindings[:object]).nil? || pin.new_record? excluded_ids.delete(pin[field]) end Proc.new { |scope| scope.where(origin: :shared, :id.nin => excluded_ids) } end end end field :version do help 'Required' visible { bindings[:object].ready_to_save? } end end show do field :model Setup::Pin.models.values.each do |m_data| field m_data[:property] end field :version field :updated_at end fields :model, :record, :version, :updated_at show_in_dashboard false end config.model Setup::Binding do navigation_label 'Configuration' weight 750 object_label_method { :label } configure :binder_model, :model configure :binder, :record configure :bind_model, :model configure :bind, :record edit do Setup::Binding.reflect_on_all_associations(:belongs_to).each do |relation| if relation.name.to_s.ends_with?('binder') field relation.name do label { relation.klass.to_s.split('::').last.to_title } read_only true visible { value.present? } help '' end else field relation.name do label { relation.klass.to_s.split('::').last.to_title } inline_edit false inline_add false visible { value.present? } help '' end end end end fields :binder_model, :binder, :bind_model, :bind, :updated_at show_in_dashboard false end config.model Setup::ParameterConfig do navigation_label 'Configuration' label 'Parameter' weight 760 configure :parent_model, :model configure :parent, :record edit do field :parent_model do read_only true help '' end field :parent do read_only true help '' end field :location do read_only true help '' end field :name do read_only true help '' end field :value end fields :parent_model, :parent, :location, :name, :value, :updated_at show_in_dashboard false end #Administration config.navigation 'Administration', icon: 'fa fa-user-secret' config.model User do weight 800 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :label } group :accounts do label 'Accounts' active true end group :credentials do label 'Credentials' active true end group :activity do label 'Activity' active true end configure :name configure :email configure :code_theme configure :roles configure :account do group :accounts label 'Current Account' end configure :api_account do group :accounts label 'API Account' end configure :accounts do group :accounts read_only { !Account.current_super_admin? } end configure :password do group :credentials end configure :password_confirmation do group :credentials end configure :key do group :credentials end configure :authentication_token do group :credentials end configure :confirmed_at do group :activity end configure :sign_in_count do group :activity end configure :current_sign_in_at do group :activity end configure :last_sign_in_at do group :activity end configure :current_sign_in_ip do group :activity end configure :last_sign_in_ip do group :activity end edit do field :picture field :name field :code_theme field :email do visible { Account.current_super_admin? } end field :roles do visible { Account.current_super_admin? } end field :account field :api_account field :accounts do visible { Account.current_super_admin? } end field :password do visible { Account.current_super_admin? } end field :password_confirmation do visible { Account.current_super_admin? } end field :key do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :authentication_token do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :confirmed_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :sign_in_count do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end end show do field :picture field :name field :email field :code_theme do label 'Code Theme' end field :account field :api_account field :accounts field :roles field :key field :authentication_token field :sign_in_count field :current_sign_in_at field :last_sign_in_at field :current_sign_in_ip field :last_sign_in_ip end list do field :picture do thumb_method :icon end field :name field :email field :account field :api_account field :accounts field :roles field :key field :authentication_token field :sign_in_count field :created_at field :updated_at end end config.model Account do weight 810 navigation_label 'Administration' object_label_method { :label } configure :_id do visible { Account.current_super_admin? } end configure :owner do visible { Account.current_super_admin? } help { nil } end configure :key do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :token do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :users do visible { Account.current_super_admin? } end configure :notification_level configure :time_zone do label 'Time Zone' end edit do field :name field :owner do visible { Account.current_super_admin? } end field :key do visible { Account.current_super_admin? } end field :token do visible { Account.current_super_admin? } end field :users do visible { Account.current_super_admin? } end field :notification_level field :time_zone end fields :_id, :name, :owner, :key, :token, :users, :notification_level, :time_zone end config.model Role do weight 810 navigation_label 'Administration' visible { User.current_super_admin? } configure :users do visible { Account.current_super_admin? } end fields :name, :users end config.model Setup::SharedName do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } fields :name, :owners, :updated_at end config.model Script do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } edit do field :name field :description field :code, :code do html_attributes do { cols: '74', rows: '15' } end code_config do { mode: 'text/x-ruby' } end end end show do field :name field :description field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end end list do field :name field :description field :code field :updated_at end fields :name, :description, :code, :updated_at end config.model Cenit::BasicToken do weight 890 navigation_label 'Administration' label 'Token' visible { User.current_super_admin? } end config.model Cenit::BasicTenantToken do weight 890 navigation_label 'Administration' label 'Tenant token' visible { User.current_super_admin? } end config.model Setup::TaskToken do weight 890 navigation_label 'Administration' parent Cenit::BasicToken visible { User.current_super_admin? } end config.model Setup::DelayedMessage do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model Setup::SystemNotification do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model RabbitConsumer do weight 850 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :to_s } configure :task_id do pretty_value do if (executor = (obj = bindings[:object]).executor) && (task = obj.executing_task) v = bindings[:view] amc = RailsAdmin.config(task.class) am = amc.abstract_model wording = task.send(amc.object_label_method) amc = RailsAdmin.config(Account) am = amc.abstract_model if (inspect_action = v.action(:inspect, am, executor)) task_path = v.show_path(model_name: task.class.to_s.underscore.gsub('/', '~'), id: task.id.to_s) v.link_to(wording, v.url_for(action: inspect_action.action_name, model_name: am.to_param, id: executor.id, params: { return_to: task_path })) else wording end.html_safe end end end list do field :channel field :tag field :executor field :task_id field :alive field :updated_at end fields :created_at, :channel, :tag, :executor, :task_id, :alive, :created_at, :updated_at end config.model Cenit::ApplicationId do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } label 'Application ID' register_instance_option(:discard_submit_buttons) { bindings[:object].instance_variable_get(:@registering) } configure :name configure :registered, :boolean configure :redirect_uris, :json_value edit do field :oauth_name do visible { bindings[:object].instance_variable_get(:@registering) } end field :redirect_uris do visible { bindings[:object].instance_variable_get(:@registering) } end end list do field :name field :registered field :tenant field :identifier field :updated_at end fields :created_at, :name, :registered, :tenant, :identifier, :created_at, :updated_at end config.model Setup::ScriptExecution do weight 840 parent { nil } navigation_label 'Administration' object_label_method { :to_s } visible { User.current_super_admin? } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end list do field :script field :description field :scheduler field :attempts_succeded field :retries field :progress field :status field :notifications field :updated_at end fields :script, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end end hidden connection role from navigarion menu require 'account' [ RailsAdmin::Config::Actions::DiskUsage, RailsAdmin::Config::Actions::SendToFlow, RailsAdmin::Config::Actions::SwitchNavigation, RailsAdmin::Config::Actions::DataType, RailsAdmin::Config::Actions::Import, #RailsAdmin::Config::Actions::EdiExport, RailsAdmin::Config::Actions::ImportSchema, RailsAdmin::Config::Actions::DeleteAll, RailsAdmin::Config::Actions::TranslatorUpdate, RailsAdmin::Config::Actions::Convert, RailsAdmin::Config::Actions::SimpleShare, RailsAdmin::Config::Actions::BulkShare, RailsAdmin::Config::Actions::Pull, RailsAdmin::Config::Actions::RetryTask, RailsAdmin::Config::Actions::DownloadFile, RailsAdmin::Config::Actions::ProcessFlow, RailsAdmin::Config::Actions::BuildGem, RailsAdmin::Config::Actions::Run, RailsAdmin::Config::Actions::Authorize, RailsAdmin::Config::Actions::SimpleDeleteDataType, RailsAdmin::Config::Actions::BulkDeleteDataType, RailsAdmin::Config::Actions::SimpleGenerate, RailsAdmin::Config::Actions::BulkGenerate, RailsAdmin::Config::Actions::SimpleExpand, RailsAdmin::Config::Actions::BulkExpand, RailsAdmin::Config::Actions::Records, RailsAdmin::Config::Actions::SwitchScheduler, RailsAdmin::Config::Actions::SimpleExport, RailsAdmin::Config::Actions::Schedule, RailsAdmin::Config::Actions::Submit, RailsAdmin::Config::Actions::Trash, RailsAdmin::Config::Actions::Inspect, RailsAdmin::Config::Actions::Copy, RailsAdmin::Config::Actions::Cancel, RailsAdmin::Config::Actions::Configure, RailsAdmin::Config::Actions::SimpleCrossShare, RailsAdmin::Config::Actions::BulkCrossShare, RailsAdmin::Config::Actions::Regist, RailsAdmin::Config::Actions::SharedCollectionIndex, RailsAdmin::Config::Actions::BulkPull, RailsAdmin::Config::Actions::CleanUp, RailsAdmin::Config::Actions::ShowRecords, RailsAdmin::Config::Actions::RunScript, RailsAdmin::Config::Actions::Play, RailsAdmin::Config::Actions::PullImport, RailsAdmin::Config::Actions::State, RailsAdmin::Config::Actions::Documentation, RailsAdmin::Config::Actions::Push ].each { |a| RailsAdmin::Config::Actions.register(a) } RailsAdmin::Config::Actions.register(:export, RailsAdmin::Config::Actions::BulkExport) [ RailsAdmin::Config::Fields::Types::JsonValue, RailsAdmin::Config::Fields::Types::JsonSchema, RailsAdmin::Config::Fields::Types::StorageFile, RailsAdmin::Config::Fields::Types::EnumEdit, RailsAdmin::Config::Fields::Types::Model, RailsAdmin::Config::Fields::Types::Record, RailsAdmin::Config::Fields::Types::HtmlErb, RailsAdmin::Config::Fields::Types::OptionalBelongsTo, RailsAdmin::Config::Fields::Types::Code ].each { |f| RailsAdmin::Config::Fields::Types.register(f) } module RailsAdmin module Config class << self def navigation(label, options) navigation_options[label.to_s] = options end def navigation_options @nav_options ||= {} end end end end RailsAdmin.config do |config| config.total_columns_width = 900 ## == PaperTrail == # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0 ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration config.authenticate_with do warden.authenticate! scope: :user unless %w(dashboard shared_collection_index index show).include?(action_name) end config.current_user_method { current_user } config.audit_with :mongoid_audit config.authorize_with :cancan config.excluded_models += [Setup::BaseOauthAuthorization, Setup::AwsAuthorization] config.actions do dashboard # mandatory # disk_usage shared_collection_index index # mandatory new { except [Setup::Event, Setup::DataType, Setup::Authorization, Setup::BaseOauthProvider] } import import_schema pull_import translator_update convert export bulk_delete show show_records run run_script edit configure play copy simple_share bulk_share simple_cross_share bulk_cross_share build_gem pull bulk_pull push download_file process_flow authorize simple_generate bulk_generate simple_expand bulk_expand records switch_navigation switch_scheduler simple_export schedule state retry_task submit inspect cancel regist simple_delete_data_type bulk_delete_data_type delete trash clean_up #show_in_app send_to_flow delete_all data_type #history_index history_show do only do [ Setup::Algorithm, Setup::Connection, Setup::Webhook, Setup::Translator, Setup::Flow, Setup::OauthClient, Setup::Oauth2Scope ] + Setup::DataType.class_hierarchy + Setup::Validator.class_hierarchy + Setup::BaseOauthProvider.class_hierarchy end visible { only.include?((obj = bindings[:object]).class) && obj.try(:shared?) } end documentation end def shared_read_only instance_eval do read_only { (obj = bindings[:object]).creator_id != User.current.id && obj.shared? } end end shared_non_editable = Proc.new do shared_read_only end #Collections config.navigation 'Collections', icon: 'fa fa-cubes' config.model Setup::Tag do visible false object_label_method { :name } fields :namespace, :name end config.model Setup::CrossCollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CrossCollectionPullParameter do visible false object_label_method { :label } configure :location, :json_value edit do field :label field :property_name field :location end show do field :label field :property_name field :location field :created_at #field :creator field :updated_at end fields :label, :property_name, :location end config.model Setup::CrossSharedCollection do weight 000 label 'Cross Shared Collection' navigation_label 'Collections' object_label_method :versioned_name visible { Account.current_super_admin? } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' configure :readme, :html_erb configure :pull_data, :json_value configure :data, :json_value configure :swagger_spec, :json_value group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :title field :image field :logo_background, :color field :name field :shared_version field :summary field :category field :authors field :pull_count field :pull_parameters field :dependencies field :readme end show do field :title field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary field :readme field :authors field :pull_count field :_id field :updated_at field :data_schemas do label 'Schemas' group :data end field :data_custom_validators do label 'Validators' group :data end field :data_data_types do label 'Data Types' group :data end field :data_connections do label 'Connections' group :api_connectors end field :data_webhooks do label 'Webhooks' group :api_connectors end field :data_connection_roles do label 'Connection Roles' group :api_connectors end field :data_flows do label 'Flows' group :workflows end field :data_events do label 'Events' group :workflows end field :data_translators do label 'Translators' group :workflows end field :data_algorithms do label 'Algorithms' group :workflows end field :data_applications do label 'Applications' group :workflows end field :data_authorizations do label 'Autorizations' group :security end field :data_oauth_clients do label 'OAuth Clients' group :security end field :data_oauth_providers do label 'OAuth Providers' group :security end field :data_oauth2_scopes do label 'OAuth 2.0 Scopes' group :security end field :data_namespaces do label 'Namespaces' group :config end end end config.model Setup::SharedCollection do weight 010 label 'Shared Collection' register_instance_option(:discard_submit_buttons) do !(a = bindings[:action]) || a.key != :edit end navigation_label 'Collections' object_label_method { :versioned_name } public_access true extra_associations do Setup::Collection.reflect_on_all_associations(:has_and_belongs_to_many).collect do |association| association = association.dup association[:name] = "data_#{association.name}".to_sym RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model) end end index_template_name :shared_collection_grid index_link_icon 'icon-th-large' group :collections group :workflows group :api_connectors do label 'Connectors' active true end group :data group :security edit do field :image do visible { !bindings[:object].instance_variable_get(:@sharing) } end field :logo_background field :name do required { true } end field :shared_version do required { true } end field :authors field :summary field :source_collection do visible { !((source_collection = bindings[:object].source_collection) && source_collection.new_record?) } inline_edit false inline_add false associated_collection_scope do source_collection = (obj = bindings[:object]).source_collection Proc.new { |scope| if obj.new_record? scope.where(id: source_collection ? source_collection.id : nil) else scope end } end end field :connections do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_connections)).nil? || v) end help do nil end pretty_value do if bindings[:object].connections.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[connection_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No connection selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && obj.source_collection && obj.source_collection.connections.present? end associated_collection_scope do source_collection = bindings[:object].source_collection connections = (source_collection && source_collection.connections) || [] Proc.new { |scope| scope.any_in(id: connections.collect { |connection| connection.id }) } end end field :dependencies do inline_add false read_only do !((v = bindings[:object].instance_variable_get(:@_selecting_dependencies)).nil? || v) end help do nil end pretty_value do if bindings[:object].dependencies.present? v = bindings[:view] ids = '' [value].flatten.select(&:present?).collect do |associated| ids += "<option value=#{associated.id} selected=true/>" amc = polymorphic? ? RailsAdmin.config(associated) : associated_model_config am = amc.abstract_model wording = associated.send(amc.object_label_method) can_see = !am.embedded? && (show_action = v.action(:show, am, associated)) can_see ? v.link_to(wording, v.url_for(action: show_action.action_name, model_name: am.to_param, id: associated.id), class: 'pjax') : wording end.to_sentence.html_safe + v.select_tag("#{bindings[:controller].instance_variable_get(:@model_config).abstract_model.param_key}[dependency_ids][]", ids.html_safe, multiple: true, style: 'display:none').html_safe else 'No dependencies selected'.html_safe end end visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) end end field :pull_parameters field :pull_count do visible { Account.current_super_admin? } end field :readme do visible do !(obj = bindings[:object]).instance_variable_get(:@_selecting_collection) && !obj.instance_variable_get(:@_selecting_connections) end end end show do field :image field :name do pretty_value do bindings[:object].versioned_name end end field :summary do pretty_value do value.html_safe end end field :readme, :html_erb field :authors field :dependencies field :pull_count field :data_namespaces do group :collections label 'Namespaces' list_fields do %w(name slug) end end field :data_flows do group :workflows label 'Flows' list_fields do %w(namespace name) #TODO Inlude a description field on Flow model end end field :data_translators do group :workflows label 'Translators' list_fields do %w(namespace name type style) end end field :data_events do group :workflows label 'Events' list_fields do %w(namespace name _type) end end field :data_algorithms do group :workflows label 'Algorithms' list_fields do %w(namespace name description) end end field :data_connection_roles do group :api_connectors label 'Connection roles' list_fields do %w(namespace name) end end field :data_webhooks do group :api_connectors label 'Webhooks' list_fields do %w(namespace name path method description) end end field :data_connections do group :api_connectors label 'Connections' list_fields do %w(namespace name url) end end field :data_data_types do group :data label 'Data types' list_fields do %w(title name slug _type) end end field :data_schemas do group :data label 'Schemas' list_fields do %w(namespace uri) end end field :data_custom_validators do group :data label 'Custom validators' list_fields do %w(namespace name _type) #TODO Include a description field for Custom Validator model end end # field :data_data TODO Include collection data field field :data_authorizations do group :security label 'Authorizations' list_fields do %w(namespace name _type) end end field :data_oauth_providers do group :security label 'OAuth providers' list_fields do %w(namespace name response_type authorization_endpoint token_endpoint token_method _type) end end field :data_oauth_clients do group :security label 'OAuth clients' list_fields do %w(provider name) end end field :data_oauth2_scopes do group :security label 'OAuth 2.0 scopes' list_fields do %w(provider name description) end end field :_id field :updated_at end list do field :image do thumb_method :icon end field :name do pretty_value do bindings[:object].versioned_name end end field :authors field :summary field :pull_count field :dependencies end end config.model Setup::CollectionAuthor do visible false object_label_method { :label } fields :name, :email end config.model Setup::CollectionPullParameter do visible false object_label_method { :label } field :label field :parameter, :enum do enum do bindings[:controller].instance_variable_get(:@shared_parameter_enum) || [bindings[:object].parameter] end end edit do field :label field :parameter field :property_name field :location, :json_value end show do field :label field :parameter field :created_at #field :creator field :updated_at end list do field :label field :parameter field :updated_at end fields :label, :parameter end config.model Setup::CollectionData do visible false object_label_method { :label } end config.model Setup::Collection do weight 020 navigation_label 'Collections' register_instance_option :label_navigation do 'My Collections' end group :workflows configure :flows do group :workflows end configure :events do group :workflows end configure :translators do group :workflows end configure :algorithms do group :workflows end configure :applications do group :workflows end group :api_connectors do label 'Connectors' active true end configure :connections do group :api_connectors end configure :webhooks do group :api_connectors end configure :connection_roles do group :api_connectors end group :data configure :data_types do group :data end configure :schemas do group :data end configure :data do group :data end configure :custom_validators do group :data end group :security configure :authorizations do group :security end configure :oauth_providers do group :security end configure :oauth_clients do group :security end configure :oauth2_scopes do group :security end group :config configure :namespaces do group :config end edit do field :title field :image field :readme do visible { Account.current_super_admin? } end field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data end show do field :title field :image field :readme, :html_erb field :name field :flows field :connection_roles field :translators field :events field :data_types field :schemas field :custom_validators field :algorithms field :applications field :webhooks field :connections field :authorizations field :oauth_providers field :oauth_clients field :oauth2_scopes field :data field :namespaces field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :title field :image do thumb_method :icon end field :name field :flows do pretty_value do value.count > 0 ? value.count : '-' end end field :connection_roles do pretty_value do value.count > 0 ? value.count : '-' end end field :translators do pretty_value do value.count > 0 ? value.count : '-' end end field :events do pretty_value do value.count > 0 ? value.count : '-' end end field :data_types do pretty_value do value.count > 0 ? value.count : '-' end end field :schemas do pretty_value do value.count > 0 ? value.count : '-' end end field :custom_validators do pretty_value do value.count > 0 ? value.count : '-' end end field :algorithms do pretty_value do value.count > 0 ? value.count : '-' end end field :applications do pretty_value do value.count > 0 ? value.count : '-' end end field :webhooks do pretty_value do value.count > 0 ? value.count : '-' end end field :connections do pretty_value do value.count > 0 ? value.count : '-' end end field :authorizations do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_providers do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth_clients do pretty_value do value.count > 0 ? value.count : '-' end end field :oauth2_scopes do pretty_value do value.count > 0 ? value.count : '-' end end field :data field :updated_at end end #Definitions config.navigation 'Definitions', icon: 'fa fa-puzzle-piece' config.model Setup::Validator do navigation_label 'Definitions' label 'Validators' weight 100 fields :namespace, :name fields :namespace, :name, :updated_at show_in_dashboard false end config.model Setup::CustomValidator do visible false configure :_type do pretty_value do value.split('::').last.to_title end end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Schema do weight 101 object_label_method { :custom_title } edit do field :namespace, :enum_edit do read_only { !bindings[:object].new_record? } end field :uri do read_only { !bindings[:object].new_record? } html_attributes do { cols: '74', rows: '1' } end end field :schema, :code do html_attributes do { cols: '74', rows: '15' } end code_config do if bindings[:object].schema_type == :json_schema { mode: 'application/json' } else { mode: 'application/xml' } end end end field :schema_data_type do inline_edit false inline_add false end end show do field :namespace field :uri field :schema do pretty_value do v = if json = JSON.parse(value) rescue nil "<code class='json'>#{JSON.pretty_generate(json).gsub('<', '&lt;').gsub('>', '&gt;')}</code>" elsif (xml = Nokogiri::XML(value)).errors.blank? "<code class='xml'>#{xml.to_xml.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else "<code>#{value}</code>" end "<pre>#{v}</pre>".html_safe end end field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :uri, :schema_data_type, :updated_at end config.model Setup::XsltValidator do parent Setup::Validator weight 102 label 'XSLT Validator' object_label_method { :custom_title } list do field :namespace field :xslt field :updated_at end fields :namespace, :name, :xslt, :updated_at end config.model Setup::EdiValidator do parent Setup::Validator weight 103 object_label_method { :custom_title } label 'EDI Validator' edit do field :namespace, :enum_edit field :name field :schema_data_type field :content_type end fields :namespace, :name, :schema_data_type, :content_type, :updated_at end config.model Setup::AlgorithmValidator do parent Setup::Validator weight 104 label 'Algorithm Validator' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :algorithm end fields :namespace, :name, :algorithm, :updated_at end config.model Setup::DataType do navigation_label 'Definitions' weight 110 label 'Data Type' object_label_method { :custom_title } visible true show_in_dashboard false configure :_type do pretty_value do value.split('::').last.to_title end end group :behavior do label 'Behavior' active false end configure :title do pretty_value do bindings[:object].custom_title end end configure :slug configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end edit do field :title, :enum_edit, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::DataType.fields[:used_memory.to_s].type.new(Setup::DataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::DataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :name field :title field :slug field :_type field :storage_size field :schema do pretty_value do v = if json = JSON.pretty_generate(value) rescue nil "<code class='json'>#{json.gsub('<', '&lt;').gsub('>', '&gt;')}</code>" else value end "<pre>#{v}</pre>".html_safe end end field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :_type, :storage_size, :updated_at end config.model Setup::JsonDataType do navigation_label 'Definitions' weight 111 label 'JSON Data Type' object_label_method { :custom_title } group :behavior do label 'Behavior' active false end configure :title configure :name do read_only { !bindings[:object].new_record? } end configure :schema, :json_schema do html_attributes do { cols: '74', rows: '15' } end # pretty_value do # "<pre><code class='json'>#{JSON.pretty_generate(value)}</code></pre>".html_safe # end end configure :storage_size, :decimal do pretty_value do if (objects = bindings[:controller].instance_variable_get(:@objects)) unless (max = bindings[:controller].instance_variable_get(:@max_storage_size)) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :schema, :json_schema do shared_read_only help { 'Required' } end field :title, &shared_non_editable field :slug field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless (max = bindings[:controller].instance_variable_get(:@max_used_memory)) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :namespace field :title field :name field :slug field :storage_size field :schema do pretty_value do "<pre><code class='ruby'>#{JSON.pretty_generate(value)}</code></pre>".html_safe end end field :before_save_callbacks field :records_methods field :data_type_methods field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end config.model Setup::FileDataType do navigation_label 'Definitions' weight 112 label 'File Data Type' object_label_method { :custom_title } group :content do label 'Content' end group :behavior do label 'Behavior' active false end configure :storage_size, :decimal do pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_storage_size) bindings[:controller].instance_variable_set(:@max_storage_size, max = objects.collect { |data_type| data_type.records_model.storage_size }.max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].records_model.storage_size }).html_safe else bindings[:view].number_to_human_size(value) end end read_only true end configure :validators do group :content inline_add false end configure :schema_data_type do group :content inline_add false inline_edit false end configure :before_save_callbacks do group :behavior inline_add false associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end configure :records_methods do group :behavior inline_add false end configure :data_type_methods do group :behavior inline_add false end configure :slug edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :title, &shared_non_editable field :slug field :validators, &shared_non_editable field :schema_data_type, &shared_non_editable field :before_save_callbacks, &shared_non_editable field :records_methods, &shared_non_editable field :data_type_methods, &shared_non_editable end list do field :namespace field :name field :slug field :validators field :schema_data_type field :used_memory do visible { Cenit.dynamic_model_loading? } pretty_value do unless max = bindings[:controller].instance_variable_get(:@max_used_memory) bindings[:controller].instance_variable_set(:@max_used_memory, max = Setup::JsonDataType.fields[:used_memory.to_s].type.new(Setup::JsonDataType.max(:used_memory))) end (bindings[:view].render partial: 'used_memory_bar', locals: { max: max, value: Setup::JsonDataType.fields[:used_memory.to_s].type.new(value) }).html_safe end end field :storage_size field :updated_at end show do field :title field :name field :slug field :validators field :storage_size field :schema_data_type field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :slug, :storage_size, :updated_at end #Connectors config.navigation 'Connectors', icon: 'fa fa-plug' config.model Setup::Parameter do visible false object_label_method { :to_s } configure :metadata, :json_value configure :value edit do field :name field :value field :description field :metadata end list do field :name field :value field :description field :metadata field :updated_at end end config.model Setup::Connection do navigation_label 'Connectors' weight 200 object_label_method { :custom_title } group :credentials do label 'Credentials' end configure :number, :string do label 'Key' html_attributes do { maxlength: 30, size: 30 } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :token, :text do html_attributes do { cols: '50', rows: '1' } end group :credentials pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:url, &shared_non_editable) field :number field :token field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :url field :number field :token field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at field :updated_at end list do field :namespace field :name field :url field :number field :token field :authorization field :updated_at end fields :namespace, :name, :url, :number, :token, :authorization, :updated_at end config.model Setup::ConnectionRole do visible false navigation_label 'Connectors' weight 210 label 'Connection Role' object_label_method { :custom_title } configure :name, :string do help 'Requiered.' html_attributes do { maxlength: 50, size: 50 } end end configure :webhooks do nested_form false end configure :connections do nested_form false end modal do field :namespace, :enum_edit field :name field :webhooks field :connections end show do field :namespace field :name field :webhooks field :connections field :_id field :created_at #field :creator field :updated_at #field :updater end edit do field :namespace, :enum_edit field :name field :webhooks field :connections end fields :namespace, :name, :webhooks, :connections, :updated_at end config.model Setup::Webhook do navigation_label 'Connectors' weight 220 object_label_method { :custom_title } configure :metadata, :json_value group :credentials do label 'Credentials' end configure :authorization do group :credentials inline_edit false end configure :authorization_handler do group :credentials end group :parameters do label 'Parameters & Headers' end configure :path, :string do help 'Requiered. Path of the webhook relative to connection URL.' html_attributes do { maxlength: 255, size: 100 } end end configure :parameters do group :parameters end configure :headers do group :parameters end configure :template_parameters do group :parameters end edit do field(:namespace, :enum_edit, &shared_non_editable) field(:name, &shared_non_editable) field(:path, &shared_non_editable) field(:method, &shared_non_editable) field(:description, &shared_non_editable) field(:metadata, :json_value, &shared_non_editable) field :authorization field(:authorization_handler, &shared_non_editable) field :parameters field :headers field :template_parameters end show do field :namespace field :name field :path field :method field :description field :metadata, :json_value field :authorization field :authorization_handler field :parameters field :headers field :template_parameters field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :path, :method, :description, :authorization, :updated_at end #Security config.navigation 'Security', icon: 'fa fa-shield' config.model Setup::OauthClient do navigation_label 'Security' label 'OAuth Client' weight 300 object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :identifier do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :secret do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end fields :provider, :name, :identifier, :secret, :tenant, :updated_at end config.model Setup::BaseOauthProvider do navigation_label 'Security' weight 310 object_label_method { :custom_title } label 'Provider' configure :_type do pretty_value do value.split('::').last.to_title end end configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :namespace, :enum_edit list do field :namespace field :name field :_type field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :tenant field :updated_at end fields :namespace, :name, :_type, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :tenant end config.model Setup::OauthProvider do weight 311 label 'OAuth 1.0 provider' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit, &shared_non_editable field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :request_token_endpoint field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :request_token_endpoint, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Provider do weight 312 label 'OAuth 2.0 provider' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end configure :refresh_token_algorithm do visible { bindings[:object].refresh_token_strategy == :custom.to_s } end edit do field :namespace, :enum_edit field :name field :response_type field :authorization_endpoint field :token_endpoint field :token_method field :scope_separator field :refresh_token_strategy field :refresh_token_algorithm end fields :namespace, :name, :response_type, :authorization_endpoint, :token_endpoint, :token_method, :scope_separator, :refresh_token_strategy, :refresh_token_algorithm, :tenant, :updated_at end config.model Setup::Oauth2Scope do navigation_label 'Security' weight 320 label 'OAuth 2.0 Scope' object_label_method { :custom_title } configure :tenant do visible { Account.current_super_admin? } read_only { true } help '' end fields :provider, :name, :description, :tenant, :updated_at end config.model Setup::Authorization do navigation_label 'Security' weight 330 object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name field :metadata end fields :namespace, :name, :status, :_type, :metadata, :updated_at show_in_dashboard false end config.model Setup::BasicAuthorization do weight 331 register_instance_option :label_navigation do 'Basic' end object_label_method { :custom_title } configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :metadata, :json_value edit do field :namespace field :name field :username field :password field :metadata end group :credentials do label 'Credentials' end configure :username do group :credentials end configure :password do group :credentials end show do field :namespace field :name field :status field :username field :password field :metadata field :_id end edit do field :namespace, :enum_edit field :name field :username field :password end fields :namespace, :name, :status, :username, :password, :updated_at end config.model Setup::OauthAuthorization do weight 332 label 'OAuth 1.0 authorization' register_instance_option :label_navigation do 'OAuth 1.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace, :enum_edit field :name field :client field :parameters field :template_parameters field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :access_token_secret do group :credentials end configure :realm_id do group :credentials end show do field :namespace field :name field :status field :client field :parameters field :template_parameters field :metadata field :_id field :access_token field :access_token_secret field :realm_id field :token_span field :authorized_at end list do field :namespace field :name field :status field :client field :updated_at end fields :namespace, :name, :status, :client, :updated_at end config.model Setup::Oauth2Authorization do weight 333 label 'OAuth 2.0 authorization' register_instance_option :label_navigation do 'OAuth 2.0' end object_label_method { :custom_title } parent Setup::Authorization configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end configure :expires_in do pretty_value do "#{value}s" if value end end edit do field :namespace, :enum_edit field :name field :client field :scopes do visible { bindings[:object].ready_to_save? } associated_collection_scope do provider = ((obj = bindings[:object]) && obj.provider) || nil Proc.new { |scope| if provider scope.where(provider_id: provider.id) else scope end } end end field :parameters do visible { bindings[:object].ready_to_save? } end field :template_parameters do visible { bindings[:object].ready_to_save? } end field :metadata end group :credentials do label 'Credentials' end configure :access_token do group :credentials end configure :token_span do group :credentials end configure :authorized_at do group :credentials end configure :refresh_token do group :credentials end configure :token_type do group :credentials end show do field :namespace field :name field :status field :client field :scopes field :parameters field :template_parameters field :metadata field :_id field :expires_in field :id_token field :token_type field :access_token field :token_span field :authorized_at field :refresh_token field :_id end fields :namespace, :name, :status, :client, :scopes, :updated_at end config.model Setup::AwsAuthorization do weight -334 object_label_method { :custom_title } configure :metadata, :json_value configure :status do pretty_value do "<span class=\"label label-#{bindings[:object].status_class}\">#{value.to_s.capitalize}</span>".html_safe end end edit do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end group :credentials do label 'Credentials' end configure :aws_access_key do group :credentials end configure :aws_secret_key do group :credentials end show do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :metadata end list do field :namespace field :name field :aws_access_key field :aws_secret_key field :seller field :merchant field :markets field :signature_method field :signature_version field :updated_at end fields :namespace, :name, :aws_access_key, :aws_secret_key, :seller, :merchant, :markets, :signature_method, :signature_version, :updated_at end config.model Cenit::OauthAccessGrant do navigation_label 'Security' label 'Access Grants' weight 340 fields :created_at, :application_id, :scope end #Compute config.navigation 'Compute', icon: 'fa fa-cog' config.model Setup::AlgorithmParameter do visible false fields :name, :type, :many, :required, :default end config.model Setup::CallLink do visible false edit do field :name do read_only true help { nil } label 'Call name' end field :link do inline_add false inline_edit false help { nil } end end fields :name, :link end config.model Setup::Algorithm do navigation_label 'Compute' weight 400 object_label_method { :custom_title } extra_associations do association = Mongoid::Relations::Metadata.new( name: :stored_outputs, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::Algorithm.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end edit do field :namespace, :enum_edit field :name field :description field :parameters field :code, :code do html_attributes do { cols: '74', rows: '15' } end code_config do { mode: 'text/x-ruby' } end help { 'Required' } end field :call_links do visible { bindings[:object].call_links.present? } end field :store_output field :output_datatype field :validate_output end show do field :namespace field :name field :description field :parameters field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end field :call_links field :_id field :stored_outputs end list do field :namespace field :name field :description field :parameters field :call_links field :updated_at end fields :namespace, :name, :description, :parameters, :call_links end config.model Setup::Translator do navigation_label 'Compute' weight 410 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :source_data_type, :target_data_type, :transformation, :target_importer, :source_exporter, :discard_chained_records ] end end edit do field :namespace, :enum_edit field :name field :type field :source_data_type do inline_edit false inline_add false visible { [:Export, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :target_data_type do inline_edit false inline_add false visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help { bindings[:object].type == :Conversion ? 'Required' : 'Optional' } end field :discard_events do visible { [:Import, :Update, :Conversion].include?(bindings[:object].type) } help "Events won't be fired for created or updated records if checked" end field :style do visible { bindings[:object].type.present? } help 'Required' end field :bulk_source do visible { bindings[:object].type == :Export && bindings[:object].style.present? && bindings[:object].source_bulkable? } end field :mime_type do label 'MIME type' visible { bindings[:object].type == :Export && bindings[:object].style.present? } end field :file_extension do visible { bindings[:object].type == :Export && !bindings[:object].file_extension_enum.empty? } help { "Extensions for #{bindings[:object].mime_type}" } end field :source_handler do visible { (t = bindings[:object]).style.present? && (t.type == :Update || (t.type == :Conversion && t.style == 'ruby')) } help { 'Handle sources on transformation' } end field :transformation, :code do visible { bindings[:object].style.present? && bindings[:object].style != 'chain' } help { 'Required' } html_attributes do { cols: '74', rows: '15' } end code_config do { mode: case bindings[:object].style when 'html.erb' 'text/html' when 'xslt' 'application/xml' else 'text/x-ruby' end } end end field :source_exporter do inline_add { bindings[:object].source_exporter.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type } help 'Required' associated_collection_scope do data_type = bindings[:object].source_data_type Proc.new { |scope| scope.all(type: :Conversion, source_data_type: data_type) } end end field :target_importer do inline_add { bindings[:object].target_importer.nil? } visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help 'Required' associated_collection_scope do translator = bindings[:object] source_data_type = if translator.source_exporter translator.source_exporter.target_data_type else translator.source_data_type end target_data_type = bindings[:object].target_data_type Proc.new { |scope| scope = scope.all(type: :Conversion, source_data_type: source_data_type, target_data_type: target_data_type) } end end field :discard_chained_records do visible { bindings[:object].style == 'chain' && bindings[:object].source_data_type && bindings[:object].target_data_type && bindings[:object].source_exporter } help "Chained records won't be saved if checked" end end show do field :namespace field :name field :type field :source_data_type field :bulk_source field :target_data_type field :discard_events field :style field :mime_type field :file_extension field :transformation do pretty_value do "<pre><code class='ruby'>#{value}</code></pre>".html_safe end end field :source_exporter field :target_importer field :discard_chained_records field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :type field :style field :mime_type field :file_extension field :updated_at end fields :namespace, :name, :type, :style, :transformation, :updated_at end config.model Setup::AlgorithmOutput do navigation_label 'Compute' weight -405 visible false configure :records_count configure :input_parameters configure :created_at do label 'Recorded at' end extra_associations do association = Mongoid::Relations::Metadata.new( name: :records, relation: Mongoid::Relations::Referenced::Many, inverse_class_name: Setup::AlgorithmOutput.to_s, class_name: Setup::AlgorithmOutput.to_s ) [RailsAdmin::Adapters::Mongoid::Association.new(association, abstract_model.model)] end show do field :created_at field :input_parameters field :records_count end fields :created_at, :input_parameters, :records_count end config.model Setup::Action do visible false navigation_label 'Compute' weight -402 object_label_method { :to_s } fields :method, :path, :algorithm end config.model Setup::Application do navigation_label 'Compute' weight 420 object_label_method { :custom_title } visible configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :slug field :actions field :application_parameters end list do field :namespace field :name field :slug field :registered field :actions field :application_parameters field :updated_at end fields :namespace, :name, :slug, :identifier, :secret_token, :registered, :actions, :application_parameters end config.model Cenit::ApplicationParameter do visible false navigation_label 'Compute' configure :group, :enum_edit list do field :name field :type field :many field :group field :description field :updated_at end fields :name, :type, :many, :group, :description end config.model Setup::Snippet do navigation_label 'Compute' weight 430 object_label_method { :custom_title } visible { Account.current_super_admin? } configure :identifier configure :registered, :boolean edit do field :namespace, :enum_edit field :name field :type field :description field :code, :code do html_attributes do { cols: '74', rows: '15' } end help { 'Required' } code_config do { mode: { 'auto': 'javascript', 'text': 'javascript', 'null': 'javascript', 'c': 'clike', 'cpp': 'clike', 'csharp': 'clike', 'csv': 'javascript', 'fsharp': 'mllike', 'java': 'clike', 'latex': 'stex', 'ocaml': 'mllike', 'scala': 'clike', 'squirrel': 'clike' }[bindings[:object].type] || bindings[:object].type } end end field :tags end show do field :namespace, :enum_edit field :name field :type field :description field :code do pretty_value do "<pre><code class='#{bindings[:object].type}'>#{value}</code></pre>".html_safe end end field :tags end list do field :namespace field :name field :type field :tags end fields :namespace, :name, :type, :description, :code, :tags end #Workflows config.navigation 'Workflows', icon: 'fa fa-cogs' config.model Setup::Flow do navigation_label 'Workflows' weight 500 object_label_method { :custom_title } register_instance_option(:form_synchronized) do if bindings[:object].not_shared? [ :custom_data_type, :data_type_scope, :scope_filter, :scope_evaluator, :lot_size, :connection_role, :webhook, :response_translator, :response_data_type ] end end Setup::FlowConfig.config_fields.each do |f| configure f.to_sym, Setup::Flow.data_type.schema['properties'][f]['type'].to_sym end edit do field :namespace, :enum_edit, &shared_non_editable field :name, &shared_non_editable field :event, :optional_belongs_to do inline_edit false inline_add false visible do (f = bindings[:object]).not_shared? || f.data_type_scope.present? end end field :translator do help I18n.t('admin.form.required') shared_read_only end field :custom_data_type, :optional_belongs_to do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] if (t = f.translator) && t.data_type.nil? unless f.data_type if f.custom_data_type_selected? f.custom_data_type = nil f.data_type_scope = nil else f.custom_data_type = f.event.try(:data_type) end end true else f.custom_data_type = nil false end end required do bindings[:object].event.present? end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_data_type') else I18n.t('admin.form.flow.target_data_type') end else I18n.t('admin.form.flow.data_type') end end end field :data_type_scope do shared_read_only visible do f = bindings[:object] #For filter scope bindings[:controller].instance_variable_set(:@_data_type, f.data_type) bindings[:controller].instance_variable_set(:@_update_field, 'translator_id') if f.shared? value.present? else f.event && (t = f.translator) && t.type != :Import && (f.custom_data_type_selected? || f.data_type) end end label do if (translator = bindings[:object].translator) if [:Export, :Conversion].include?(translator.type) I18n.t('admin.form.flow.source_scope') else I18n.t('admin.form.flow.target_scope') end else I18n.t('admin.form.flow.data_type_scope') end end help I18n.t('admin.form.required') end field :scope_filter do shared_read_only visible do f = bindings[:object] f.scope_symbol == :filtered end partial 'form_triggers' help I18n.t('admin.form.required') end field :scope_evaluator do inline_add false inline_edit false shared_read_only visible do f = bindings[:object] f.scope_symbol == :evaluation end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end help I18n.t('admin.form.required') end field :lot_size do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.custom_data_type_selected? && (f.event.blank? || f.data_type.blank? || (f.data_type_scope.present? && f.scope_symbol != :event_source)) end end field :webhook do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end help I18n.t('admin.form.required') end field :authorization do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :connection_role do visible do ((f = bindings[:object]).shared? && f.webhook.present?) || (t = f.translator) && [:Import, :Export].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end end field :before_submit do shared_read_only visible do f = bindings[:object] (t = f.translator) && [:Import].include?(t.type) && ((f.persisted? || f.custom_data_type_selected? || f.data_type) && (t.type == :Import || f.event.blank? || f.data_type.blank? || f.data_type_scope.present?)) end associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :response_translator do shared_read_only visible do f = bindings[:object] (t = f.translator) && t.type == :Export && f.ready_to_save? end associated_collection_scope do Proc.new { |scope| scope.where(type: :Import) } end end field :response_data_type do inline_edit false inline_add false shared_read_only visible do f = bindings[:object] (resp_t = f.response_translator) && resp_t.type == :Import && resp_t.data_type.nil? end help I18n.t('admin.form.required') end field :discard_events do visible do f = bindings[:object] ((f.translator && f.translator.type == :Import) || f.response_translator.present?) && f.ready_to_save? end help I18n.t('admin.form.flow.events_wont_be_fired') end field :active do visible do f = bindings[:object] f.ready_to_save? end end field :notify_request do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help I18n.t('admin.form.flow.notify_request') end field :notify_response do visible do f = bindings[:object] (t = f.translator) && [:Import, :Export].include?(t.type) && f.ready_to_save? end help help I18n.t('admin.form.flow.notify_response') end field :after_process_callbacks do shared_read_only visible do bindings[:object].ready_to_save? end help I18n.t('admin.form.flow.after_process_callbacks') associated_collection_scope do Proc.new { |scope| scope.where(:parameters.with_size => 1) } end end end show do field :namespace field :name field :active field :event field :translator field :custom_data_type field :data_type_scope field :scope_filter field :scope_evaluator field :lot_size field :webhook field :authorization field :connection_role field :before_submit field :response_translator field :response_data_type field :discard_events field :notify_request field :notify_response field :after_process_callbacks field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :active field :event field :translator field :updated_at end fields :namespace, :name, :active, :event, :translator, :updated_at end config.model Setup::Event do navigation_label 'Workflows' weight 510 object_label_method { :custom_title } visible false configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :namespace, :enum_edit field :name end show do field :namespace field :name field :_type field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :_type field :updated_at end fields :namespace, :name, :_type, :updated_at end config.model Setup::Observer do navigation_label 'Workflows' weight 511 label 'Data Event' object_label_method { :custom_title } edit do field :namespace, :enum_edit field :name field :data_type do inline_add false inline_edit false associated_collection_scope do data_type = bindings[:object].data_type Proc.new { |scope| if data_type scope.where(id: data_type.id) else scope end } end help 'Required' end field :trigger_evaluator do visible { (obj = bindings[:object]).data_type.blank? || obj.trigger_evaluator.present? || obj.triggers.nil? } associated_collection_scope do Proc.new { |scope| scope.all.or(:parameters.with_size => 1).or(:parameters.with_size => 2) } end end field :triggers do visible do bindings[:controller].instance_variable_set(:@_data_type, data_type = bindings[:object].data_type) bindings[:controller].instance_variable_set(:@_update_field, 'data_type_id') data_type.present? && !bindings[:object].trigger_evaluator.present? end partial 'form_triggers' help false end end show do field :namespace field :name field :data_type field :triggers field :trigger_evaluator field :_id field :created_at #field :creator field :updated_at #field :updater end fields :namespace, :name, :data_type, :triggers, :trigger_evaluator, :updated_at end config.model Setup::Scheduler do navigation_label 'Workflows' weight 512 object_label_method { :custom_title } configure :expression, :json_value edit do field :namespace, :enum_edit field :name field :expression do visible true label 'Scheduling type' help 'Configure scheduler' partial :scheduler html_attributes do { rows: '1' } end end end show do field :namespace field :name field :expression field :_id field :created_at #field :creator field :updated_at #field :updater end list do field :namespace field :name field :expression field :activated field :updated_at end fields :namespace, :name, :expression, :activated, :updated_at end #Monitors config.navigation 'Monitors', icon: 'fa fa-heartbeat' config.model Setup::Notification do navigation_label 'Monitors' weight 600 object_label_method { :label } show_in_dashboard false configure :created_at configure :type do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value.to_s.capitalize}</label>".html_safe end end configure :message do pretty_value do "<label style='color:#{bindings[:object].color}'>#{value}</label>".html_safe end end configure :attachment, :storage_file list do field :created_at do visible do if (account = Account.current) account.notifications_listed_at = Time.now end true end end field :type field :message field :attachment field :task field :updated_at end end config.model Setup::Task do navigation_label 'Monitors' weight 610 object_label_method { :to_s } show_in_dashboard false configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :updated_at end config.model Setup::FlowExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :flow, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeGeneration do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataTypeExpansion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Translation do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::DataImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :translator, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Push do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :source_collection, :shared_collection, :description, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::BasePull do navigation_label 'Monitors' visible false label 'Pull' object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :_type do pretty_value do value.split('::').last.to_title end end edit do field :description end fields :_type, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::PullImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :data do label 'Pull data' end edit do field :description end fields :data, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SharedCollectionPull do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :shared_collection, :pull_request, :pulled_request, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::SchemasImport do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :base_uri, :data, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Deletion do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end configure :deletion_model do label 'Model' pretty_value do if value v = bindings[:view] amc = RailsAdmin.config(value) am = amc.abstract_model wording = amc.navigation_label + ' > ' + amc.label can_see = !am.embedded? && (index_action = v.action(:index, am)) (can_see ? v.link_to(amc.contextualized_label(:menu), v.url_for(action: index_action.action_name, model_name: am.to_param), class: 'pjax') : wording).html_safe end end end edit do field :description end fields :deletion_model, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::AlgorithmExecution do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :algorithm, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Submission do navigation_label 'Monitors' visible false object_label_method { :to_s } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end fields :webhook, :connection, :authorization, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications, :updated_at end config.model Setup::Storage do navigation_label 'Monitors' show_in_dashboard false weight 620 object_label_method { :label } configure :filename do label 'File name' pretty_value { bindings[:object].storage_name } end configure :length do label 'Size' pretty_value do if objects = bindings[:controller].instance_variable_get(:@objects) unless max = bindings[:controller].instance_variable_get(:@max_length) bindings[:controller].instance_variable_set(:@max_length, max = objects.collect { |storage| storage.length }.reject(&:nil?).max) end (bindings[:view].render partial: 'size_bar', locals: { max: max, value: bindings[:object].length }).html_safe else bindings[:view].number_to_human_size(value) end end end configure :storer_model, :model do label 'Model' end configure :storer_object, :record do label 'Object' end configure :storer_property do label 'Property' end list do field :storer_model field :storer_object field :storer_property field :filename field :contentType field :length field :updated_at end fields :storer_model, :storer_object, :storer_property, :filename, :contentType, :length end #Configuration config.navigation 'Configuration', icon: 'fa fa-sliders' config.model Setup::Namespace do navigation_label 'Configuration' weight 700 fields :name, :slug, :updated_at show_in_dashboard false end config.model Setup::DataTypeConfig do navigation_label 'Configuration' label 'Data Type Config' weight 710 configure :data_type do read_only true end fields :data_type, :slug, :navigation_link, :updated_at show_in_dashboard false end config.model Setup::FlowConfig do navigation_label 'Configuration' label 'Flow Config' weight 720 configure :flow do read_only true end fields :flow, :active, :notify_request, :notify_response, :discard_events show_in_dashboard false end config.model Setup::ConnectionConfig do navigation_label 'Configuration' label 'Connection Config' weight 730 configure :connection do read_only true end configure :number do label 'Key' end fields :connection, :number, :token show_in_dashboard false end config.model Setup::Pin do navigation_label 'Configuration' weight 740 object_label_method :to_s configure :model, :model configure :record, :record edit do field :record_model do label 'Model' help 'Required' end Setup::Pin.models.values.each do |m_data| field m_data[:property] do inline_add false inline_edit false help 'Required' visible { bindings[:object].record_model == m_data[:model_name] } associated_collection_scope do field = "#{m_data[:property]}_id".to_sym excluded_ids = Setup::Pin.where(field.exists => true).collect(&field) unless (pin = bindings[:object]).nil? || pin.new_record? excluded_ids.delete(pin[field]) end Proc.new { |scope| scope.where(origin: :shared, :id.nin => excluded_ids) } end end end field :version do help 'Required' visible { bindings[:object].ready_to_save? } end end show do field :model Setup::Pin.models.values.each do |m_data| field m_data[:property] end field :version field :updated_at end fields :model, :record, :version, :updated_at show_in_dashboard false end config.model Setup::Binding do navigation_label 'Configuration' weight 750 object_label_method { :label } configure :binder_model, :model configure :binder, :record configure :bind_model, :model configure :bind, :record edit do Setup::Binding.reflect_on_all_associations(:belongs_to).each do |relation| if relation.name.to_s.ends_with?('binder') field relation.name do label { relation.klass.to_s.split('::').last.to_title } read_only true visible { value.present? } help '' end else field relation.name do label { relation.klass.to_s.split('::').last.to_title } inline_edit false inline_add false visible { value.present? } help '' end end end end fields :binder_model, :binder, :bind_model, :bind, :updated_at show_in_dashboard false end config.model Setup::ParameterConfig do navigation_label 'Configuration' label 'Parameter' weight 760 configure :parent_model, :model configure :parent, :record edit do field :parent_model do read_only true help '' end field :parent do read_only true help '' end field :location do read_only true help '' end field :name do read_only true help '' end field :value end fields :parent_model, :parent, :location, :name, :value, :updated_at show_in_dashboard false end #Administration config.navigation 'Administration', icon: 'fa fa-user-secret' config.model User do weight 800 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :label } group :accounts do label 'Accounts' active true end group :credentials do label 'Credentials' active true end group :activity do label 'Activity' active true end configure :name configure :email configure :code_theme configure :roles configure :account do group :accounts label 'Current Account' end configure :api_account do group :accounts label 'API Account' end configure :accounts do group :accounts read_only { !Account.current_super_admin? } end configure :password do group :credentials end configure :password_confirmation do group :credentials end configure :key do group :credentials end configure :authentication_token do group :credentials end configure :confirmed_at do group :activity end configure :sign_in_count do group :activity end configure :current_sign_in_at do group :activity end configure :last_sign_in_at do group :activity end configure :current_sign_in_ip do group :activity end configure :last_sign_in_ip do group :activity end edit do field :picture field :name field :code_theme field :email do visible { Account.current_super_admin? } end field :roles do visible { Account.current_super_admin? } end field :account field :api_account field :accounts do visible { Account.current_super_admin? } end field :password do visible { Account.current_super_admin? } end field :password_confirmation do visible { Account.current_super_admin? } end field :key do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :authentication_token do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :confirmed_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :sign_in_count do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_at do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :current_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end field :last_sign_in_ip do visible { !bindings[:object].new_record? && Account.current_super_admin? } end end show do field :picture field :name field :email field :code_theme do label 'Code Theme' end field :account field :api_account field :accounts field :roles field :key field :authentication_token field :sign_in_count field :current_sign_in_at field :last_sign_in_at field :current_sign_in_ip field :last_sign_in_ip end list do field :picture do thumb_method :icon end field :name field :email field :account field :api_account field :accounts field :roles field :key field :authentication_token field :sign_in_count field :created_at field :updated_at end end config.model Account do weight 810 navigation_label 'Administration' object_label_method { :label } configure :_id do visible { Account.current_super_admin? } end configure :owner do visible { Account.current_super_admin? } help { nil } end configure :key do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :token do pretty_value do (value || '<i class="icon-lock"/>').html_safe end end configure :users do visible { Account.current_super_admin? } end configure :notification_level configure :time_zone do label 'Time Zone' end edit do field :name field :owner do visible { Account.current_super_admin? } end field :key do visible { Account.current_super_admin? } end field :token do visible { Account.current_super_admin? } end field :users do visible { Account.current_super_admin? } end field :notification_level field :time_zone end fields :_id, :name, :owner, :key, :token, :users, :notification_level, :time_zone end config.model Role do weight 810 navigation_label 'Administration' visible { User.current_super_admin? } configure :users do visible { Account.current_super_admin? } end fields :name, :users end config.model Setup::SharedName do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } fields :name, :owners, :updated_at end config.model Script do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } edit do field :name field :description field :code, :code do html_attributes do { cols: '74', rows: '15' } end code_config do { mode: 'text/x-ruby' } end end end show do field :name field :description field :code do pretty_value do v = value.gsub('<', '&lt;').gsub('>', '&gt;') "<pre><code class='ruby'>#{v}</code></pre>".html_safe end end end list do field :name field :description field :code field :updated_at end fields :name, :description, :code, :updated_at end config.model Cenit::BasicToken do weight 890 navigation_label 'Administration' label 'Token' visible { User.current_super_admin? } end config.model Cenit::BasicTenantToken do weight 890 navigation_label 'Administration' label 'Tenant token' visible { User.current_super_admin? } end config.model Setup::TaskToken do weight 890 navigation_label 'Administration' parent Cenit::BasicToken visible { User.current_super_admin? } end config.model Setup::DelayedMessage do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model Setup::SystemNotification do weight 880 navigation_label 'Administration' visible { User.current_super_admin? } end config.model RabbitConsumer do weight 850 navigation_label 'Administration' visible { User.current_super_admin? } object_label_method { :to_s } configure :task_id do pretty_value do if (executor = (obj = bindings[:object]).executor) && (task = obj.executing_task) v = bindings[:view] amc = RailsAdmin.config(task.class) am = amc.abstract_model wording = task.send(amc.object_label_method) amc = RailsAdmin.config(Account) am = amc.abstract_model if (inspect_action = v.action(:inspect, am, executor)) task_path = v.show_path(model_name: task.class.to_s.underscore.gsub('/', '~'), id: task.id.to_s) v.link_to(wording, v.url_for(action: inspect_action.action_name, model_name: am.to_param, id: executor.id, params: { return_to: task_path })) else wording end.html_safe end end end list do field :channel field :tag field :executor field :task_id field :alive field :updated_at end fields :created_at, :channel, :tag, :executor, :task_id, :alive, :created_at, :updated_at end config.model Cenit::ApplicationId do weight 830 navigation_label 'Administration' visible { User.current_super_admin? } label 'Application ID' register_instance_option(:discard_submit_buttons) { bindings[:object].instance_variable_get(:@registering) } configure :name configure :registered, :boolean configure :redirect_uris, :json_value edit do field :oauth_name do visible { bindings[:object].instance_variable_get(:@registering) } end field :redirect_uris do visible { bindings[:object].instance_variable_get(:@registering) } end end list do field :name field :registered field :tenant field :identifier field :updated_at end fields :created_at, :name, :registered, :tenant, :identifier, :created_at, :updated_at end config.model Setup::ScriptExecution do weight 840 parent { nil } navigation_label 'Administration' object_label_method { :to_s } visible { User.current_super_admin? } configure :attempts_succeded, :text do label 'Attempts/Succedded' end edit do field :description end list do field :script field :description field :scheduler field :attempts_succeded field :retries field :progress field :status field :notifications field :updated_at end fields :script, :description, :scheduler, :attempts_succeded, :retries, :progress, :status, :notifications end end
module Tabula ## # a "collection" of TextElements class TextChunk < ZoneEntity attr_accessor :font, :font_size, :text_elements, :width_of_space ## # initialize a new TextChunk from a TextElement def self.create_from_text_element(text_element) raise TypeError, "argument is not a TextElement" unless text_element.instance_of?(TextElement) tc = self.new(*text_element.tlwh) tc.text_elements = [text_element] return tc end require 'ruby-debug' # # group an iterable of TextChunk into a list of Line def self.group_by_lines(text_chunks) lines = text_chunks.inject([]) do |memo, te| # if te.text.start_with?('Otras carnes rojas') # debugger # end next memo if te.text =~ ONLY_SPACES_RE l = memo.find { |line| line.horizontal_overlap_ratio(te) >= 0.5 } if l.nil? l = Line.new memo << l end l << te memo end lines.map!(&:remove_sequential_spaces!) end ## # returns a list of column boundaries (x axis) # +lines+ must be an array of lines sorted by their +top+ attribute def self.column_positions(lines) init = lines.first.text_elements.map { |text_chunk| Tabula::ZoneEntity.new(*text_chunk.tlwh) } regions = lines[1..-1] .inject(init) do |column_regions, line| line_text_elements = line.text_elements.clone column_regions.each do |cr| overlaps = line_text_elements .select { |te| te.text !~ ONLY_SPACES_RE && cr.horizontally_overlaps?(te) } overlaps.inject(cr) do |memo, te| cr.merge!(te) end line_text_elements = line_text_elements - overlaps end column_regions += line_text_elements.map { |te| Tabula::ZoneEntity.new(*te.tlwh) } end regions.map { |r| r.right.round(2) }.uniq end ## # add a TextElement to this TextChunk def <<(text_element) self.text_elements << text_element self.merge!(text_element) end def merge!(other) if other.instance_of?(TextChunk) if (self <=> other) < 0 self.text_elements = self.text_elements + other.text_elements else self.text_elements = other.text_elements + self.text_elements end end super(other) end ## # split this TextChunk vertically # (in place, returns the remaining chunk) def split_vertically!(y) raise "Not Implemented" end def text self.text_elements.map(&:text).join end def inspect "#<TextChunk: #{self.top.round(2)},#{self.left.round(2)},#{self.bottom.round(2)},#{right.round(2)} '#{self.text}'>" end def to_h super.merge(:text => self.text) end end end remove debugger module Tabula ## # a "collection" of TextElements class TextChunk < ZoneEntity attr_accessor :font, :font_size, :text_elements, :width_of_space ## # initialize a new TextChunk from a TextElement def self.create_from_text_element(text_element) raise TypeError, "argument is not a TextElement" unless text_element.instance_of?(TextElement) tc = self.new(*text_element.tlwh) tc.text_elements = [text_element] return tc end # # group an iterable of TextChunk into a list of Line def self.group_by_lines(text_chunks) lines = text_chunks.inject([]) do |memo, te| # if te.text.start_with?('Otras carnes rojas') # debugger # end next memo if te.text =~ ONLY_SPACES_RE l = memo.find { |line| line.horizontal_overlap_ratio(te) >= 0.5 } if l.nil? l = Line.new memo << l end l << te memo end lines.map!(&:remove_sequential_spaces!) end ## # returns a list of column boundaries (x axis) # +lines+ must be an array of lines sorted by their +top+ attribute def self.column_positions(lines) init = lines.first.text_elements.map { |text_chunk| Tabula::ZoneEntity.new(*text_chunk.tlwh) } regions = lines[1..-1] .inject(init) do |column_regions, line| line_text_elements = line.text_elements.clone column_regions.each do |cr| overlaps = line_text_elements .select { |te| te.text !~ ONLY_SPACES_RE && cr.horizontally_overlaps?(te) } overlaps.inject(cr) do |memo, te| cr.merge!(te) end line_text_elements = line_text_elements - overlaps end column_regions += line_text_elements.map { |te| Tabula::ZoneEntity.new(*te.tlwh) } end regions.map { |r| r.right.round(2) }.uniq end ## # add a TextElement to this TextChunk def <<(text_element) self.text_elements << text_element self.merge!(text_element) end def merge!(other) if other.instance_of?(TextChunk) if (self <=> other) < 0 self.text_elements = self.text_elements + other.text_elements else self.text_elements = other.text_elements + self.text_elements end end super(other) end ## # split this TextChunk vertically # (in place, returns the remaining chunk) def split_vertically!(y) raise "Not Implemented" end def text self.text_elements.map(&:text).join end def inspect "#<TextChunk: #{self.top.round(2)},#{self.left.round(2)},#{self.bottom.round(2)},#{right.round(2)} '#{self.text}'>" end def to_h super.merge(:text => self.text) end end end
require 'faraday' require 'oj' require_relative '../logging' module TogglV8 module Connection include Logging DELAY_SEC = 1 MAX_RETRIES = 3 API_TOKEN = 'api_token' TOGGL_FILE = '.toggl' def self.open(username=nil, password=API_TOKEN, url=nil, opts={}) raise 'Missing URL' if url.nil? Faraday.new(:url => url, :ssl => {:verify => true}) do |faraday| faraday.request :url_encoded faraday.response :logger, Logger.new('faraday.log') if opts[:log] faraday.adapter Faraday.default_adapter faraday.headers = { "Content-Type" => "application/json" } faraday.basic_auth username, password end end def requireParams(params, fields=[]) raise ArgumentError, 'params is not a Hash' unless params.is_a? Hash return if fields.empty? errors = [] for f in fields errors.push("params[#{f}] is required") unless params.has_key?(f) end raise ArgumentError, errors.join(', ') if !errors.empty? end def _call_api(procs) # logger.debug(procs[:debug_output].call) full_resp = nil i = 0 loop do i += 1 full_resp = procs[:api_call].call logger.ap(full_resp.env, :debug) break if full_resp.status != 429 || i >= MAX_RETRIES sleep(DELAY_SEC) end raise full_resp.headers['warning'] if full_resp.headers['warning'] raise "HTTP Status: #{full_resp.status}" unless full_resp.success? return {} if full_resp.body.nil? || full_resp.body == 'null' full_resp end def get(resource, params={}) query_params = params.map { |k,v| "#{k}=#{v}" }.join('&') resource += "?#{query_params}" unless query_params.empty? resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "GET #{resource}" }, api_call: lambda { self.conn.get(resource) } ) return {} if full_resp == {} begin resp = Oj.load(full_resp.body) return resp['data'] if resp.respond_to?(:has_key?) && resp.has_key?('data') return resp rescue Oj::ParseError return full_resp.body end end def post(resource, data='') resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "POST #{resource} / #{data}" }, api_call: lambda { self.conn.post(resource, Oj.dump(data)) } ) return {} if full_resp == {} resp = Oj.load(full_resp.body) resp['data'] end def put(resource, data='') resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "PUT #{resource} / #{data}" }, api_call: lambda { self.conn.put(resource, Oj.dump(data)) } ) return {} if full_resp == {} resp = Oj.load(full_resp.body) resp['data'] end def delete(resource) resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "DELETE #{resource}" }, api_call: lambda { self.conn.delete(resource) } ) return {} if full_resp == {} full_resp.body end end end Comment out use of awesome_print. require 'faraday' require 'oj' require_relative '../logging' module TogglV8 module Connection include Logging DELAY_SEC = 1 MAX_RETRIES = 3 API_TOKEN = 'api_token' TOGGL_FILE = '.toggl' def self.open(username=nil, password=API_TOKEN, url=nil, opts={}) raise 'Missing URL' if url.nil? Faraday.new(:url => url, :ssl => {:verify => true}) do |faraday| faraday.request :url_encoded faraday.response :logger, Logger.new('faraday.log') if opts[:log] faraday.adapter Faraday.default_adapter faraday.headers = { "Content-Type" => "application/json" } faraday.basic_auth username, password end end def requireParams(params, fields=[]) raise ArgumentError, 'params is not a Hash' unless params.is_a? Hash return if fields.empty? errors = [] for f in fields errors.push("params[#{f}] is required") unless params.has_key?(f) end raise ArgumentError, errors.join(', ') if !errors.empty? end def _call_api(procs) # logger.debug(procs[:debug_output].call) full_resp = nil i = 0 loop do i += 1 full_resp = procs[:api_call].call # logger.ap(full_resp.env, :debug) break if full_resp.status != 429 || i >= MAX_RETRIES sleep(DELAY_SEC) end raise full_resp.headers['warning'] if full_resp.headers['warning'] raise "HTTP Status: #{full_resp.status}" unless full_resp.success? return {} if full_resp.body.nil? || full_resp.body == 'null' full_resp end def get(resource, params={}) query_params = params.map { |k,v| "#{k}=#{v}" }.join('&') resource += "?#{query_params}" unless query_params.empty? resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "GET #{resource}" }, api_call: lambda { self.conn.get(resource) } ) return {} if full_resp == {} begin resp = Oj.load(full_resp.body) return resp['data'] if resp.respond_to?(:has_key?) && resp.has_key?('data') return resp rescue Oj::ParseError return full_resp.body end end def post(resource, data='') resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "POST #{resource} / #{data}" }, api_call: lambda { self.conn.post(resource, Oj.dump(data)) } ) return {} if full_resp == {} resp = Oj.load(full_resp.body) resp['data'] end def put(resource, data='') resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "PUT #{resource} / #{data}" }, api_call: lambda { self.conn.put(resource, Oj.dump(data)) } ) return {} if full_resp == {} resp = Oj.load(full_resp.body) resp['data'] end def delete(resource) resource.gsub!('+', '%2B') full_resp = _call_api(debug_output: lambda { "DELETE #{resource}" }, api_call: lambda { self.conn.delete(resource) } ) return {} if full_resp == {} full_resp.body end end end
Pod::Spec.new do |s| s.name = "ios-cloudfiles" s.version = "1.0.4" s.summary = "Rackspace Cloud Files SDK for iOS http://www.rackspace.com" s.homepage = "https://github.com/felipecarreramo/ios-cloudfiles" s.license = "MIT" s.author = { "Felipe Carrera" => "" } s.source = { :git => "https://github.com/felipecarreramo/ios-cloudfiles.git", :tag => s.version.to_s } s.source_files = "RackspaceCloudFiles/Source", "RackspaceCloudFiles/Source/*.{h,m}" s.requires_arc = true s.platform = :ios, '8.0' end 1.0.5 Pod::Spec.new do |s| s.name = "ios-cloudfiles" s.version = "1.0.5" s.summary = "Rackspace Cloud Files SDK for iOS http://www.rackspace.com" s.homepage = "https://github.com/felipecarreramo/ios-cloudfiles" s.license = "MIT" s.author = { "Felipe Carrera" => "" } s.source = { :git => "https://github.com/felipecarreramo/ios-cloudfiles.git", :tag => s.version.to_s } s.source_files = "RackspaceCloudFiles/Source", "RackspaceCloudFiles/Source/*.{h,m}" s.requires_arc = true s.platform = :ios, '8.0' end
class Robot DIRECTIONS = %w(NORTH EAST SOUTH WEST) TABLE_WIDTH = 5 INTEGER_REGEX = /^\d+$/ def execute_command command command.strip! if command =~ /^PLACE\s+(.+)$/ x, y, direction = $1.split /\s*,\s*/ return unless x =~ INTEGER_REGEX && y =~ INTEGER_REGEX && direction =~ /^(#{DIRECTIONS.join('|')})$/ return if x.to_i > TABLE_WIDTH @coords = [x, y, direction].join(',') return end @coords if command == 'REPORT' end end * Refactor. Check whether passed x, y coords are integer and convert to Integer in one go. class Robot DIRECTIONS = %w(NORTH EAST SOUTH WEST) TABLE_WIDTH = 5 INTEGER_REGEX = /^\d+$/ def execute_command command command.strip! if command =~ /^PLACE\s+(.+)$/ x, y, direction = $1.split /\s*,\s*/ begin x, y = Integer(x), Integer(y) rescue ArgumentError return end return unless direction =~ /^(#{DIRECTIONS.join('|')})$/ return if x > TABLE_WIDTH @coords = [x, y, direction].join(',') return end @coords if command == 'REPORT' end end
module Toy module Dynamo VERSION = "0.1.11" end end bump version module Toy module Dynamo VERSION = "0.1.12" end end
# # adapted from: # http://www.samsaffron.com/archive/2008/02/02/Redo+your+migrations+in+Rails+and+keep+your+data # NOTE: 09-26-2009 knowuh: these migrations do not seem to work with models which have our scoped name-spaces. # def username(enviro) dbconfig = YAML::load(File.open('config/database.yml')) dbconfig[enviro]["username"] end def password(enviro) dbconfig = YAML::load(File.open('config/database.yml')) dbconfig[enviro]["password"] end def database(enviro) dbconfig = YAML::load(File.open('config/database.yml')) dbconfig[enviro]["database"] end # something like this will ONLY WORKO ON MYSQL! def clone_production %w|test development|.each do |enviro| puts "trying with environment #{enviro}" %x[ mysqldump --add-drop-table -u #{username(enviro)} -p#{password(enviro)} #{database(enviro)} | mysql -u #{username('production')} -p#{password('production')} #{database('production')} ] end end def interesting_tables tables = ActiveRecord::Base.connection.tables.sort tables.reject! do |tbl| %w{schema_migrations sessions roles_users admin_projects}.include?(tbl) end tables end namespace :db do desc "clone the production db to development and testing (MYSQL ONLY!)" task :clone do clone_production end namespace :backup do desc "Reload the database and rerun migrations" task :redo do Rake::Task['db:backup:write'].invoke Rake::Task['db:reset'].invoke Rake::Task['db:backup:read'].invoke end desc "Saves the db to yaml fixures in config/db/backup." task :save => :environment do dir = RAILS_ROOT + '/config/db_backup' FileUtils.mkdir_p(dir) FileUtils.chdir(dir) do interesting_tables.each do |tbl| klass = tbl.classify.constantize File.open("#{tbl}.yaml", 'w') do |f| attributes = klass.find(:all).collect { |m| m.attributes } f.write YAML.dump(attributes) end end end end desc "Loads the db from yaml fixures in config/db/backup" task :load => [:environment] do dir = RAILS_ROOT + '/config/db_backup' FileUtils.chdir(dir) do interesting_tables.each do |tbl| ActiveRecord::Base.transaction do begin klass = tbl.classify.constantize klass.destroy_all klass.reset_column_information puts "Loading #{tbl}..." table_path = "#{tbl}.yaml" YAML.load_file(table_path).each do |fixture| data = {} klass.columns.each do |c| # filter out missing columns data[c.name] = fixture[c.name] if fixture[c.name] end ActiveRecord::Base.connection.execute "INSERT INTO #{tbl} (#{data.keys.map{|kk| "#{tbl}.#{kk}"}.join(",")}) VALUES (#{data.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert' end rescue puts "failed to load table #{tbl}" end end end end end desc "Save the interface/probe configuration data to yaml fixtures in config/probe_configurations." task :save_probe_configurations => :environment do dir = RAILS_ROOT + '/config/probe_configurations' FileUtils.chdir(dir) do tables = %w{device_configs data_filters vendor_interfaces physical_units calibrations probe_types} tables.each do |tbl| puts "writing #{dir}/#{tbl}.yaml" File.open("#{tbl}.yaml", 'w') do |f| attributes = tbl.classify.constantize.find(:all).collect { |m| m.attributes } f.write YAML.dump(attributes) end end end end desc "Load just the probe configurations from yaml fixtures in config/probe_configurations." task :load_probe_configurations => :environment do dir = RAILS_ROOT + '/config/probe_configurations' user_id = User.site_admin.id FileUtils.chdir(dir) do tables = %w{device_configs data_filters vendor_interfaces physical_units calibrations probe_types} tables.each do |tbl| ActiveRecord::Base.transaction do begin klass = tbl.classify.constantize klass.destroy_all klass.reset_column_information puts "Loading #{tbl}..." table_path = "#{tbl}.yaml" YAML.load_file(table_path).each do |fixture| data = {} klass.columns.each do |c| # filter out missing columns data[c.name] = fixture[c.name] if fixture[c.name] # if there is a field named user_id set it's value to the id for the rites site admin if c.name == 'user_id' data[c.name] = user_id end end ActiveRecord::Base.connection.execute "INSERT INTO #{tbl} (#{data.keys.map{|kk| "#{tbl}.#{kk}"}.join(",")}) VALUES (#{data.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert' end rescue StandardError => e puts e puts "failed to load table #{tbl}" end end end end end desc "Dump just the Factory Girl factory definitions from the current db" task :dump_defs_to_factory_girl => :environment do @just_factories = true Rake::Task['db:backup:dump_to_factory_girl'].invoke end desc "Dump the db to a rough Factory Girl format" task :dump_to_factory_girl => :environment do @skip_attrs = ["id", "created_at", "updated_at", "uuid"] @namespaced = {"maven_jnlp_" => "MavenJnlp::", "admin_" => "Admin::", "dataservice_" => "Dataservice::", "otrunk_example_" => "OtrunkExample::", "portal_" => "Portal::"} # @non_rich_joins = ["jars_versioned_jnlps","portal_courses_grade_levels","portal_grade_levels_teachers"] ActiveRecord::Base.connection.tables.each do |table| print "Dumping #{table}... " tablename = table.singularize classname = "" @namespaced.each do |k,v| if table =~ /^#{k}/ classname = ", :class => #{v}#{tablename.sub(/^#{k}/,'').classify}" end end cols = [] ActiveRecord::Base.connection.columns(table).each do |col| cols << col.name end f = nil if cols.include?("id") f = File.open("#{RAILS_ROOT}/features/factories/#{table}.rb", "w") f.write "Factory.define :#{tablename}#{classname} do |f|\n" f.write "end\n\n" else if @just_factories # no op else f = File.open("#{RAILS_ROOT}/features/factories/#{table}.rb", "w") f.write "# #{table}: This is a non-rich join table\n\n" end end objs = ActiveRecord::Base.connection.execute "SELECT * from #{table}" objs.each do |o| if ! @just_factories if cols.include?("id") write_factory(f,tablename,cols,o) else write_joins(f,table,cols,o) end end end if f f.flush f.close end print " done.\n" end end def write_factory(file, table, cols, vals) tvals = [cols,vals].transpose out_vals = [] tvals.each do |val| next if @skip_attrs.include?(val[0]) out_vals << ":#{val[0]} => '#{val[1].to_s.sub(/'/,'\\\'')}'" end file.write("Factory.create(:#{table},{\n " + out_vals.join(",\n ") + "\n})\n") end def write_joins(file, table, cols, vals) return if @just_factories tvals = [cols,vals].transpose colArr = [] valArr = [] tvals.each do |val| next if @skip_attrs.include?(val[0]) colArr << val[0] valArr << val[1].to_s.sub(/'/,'\\\'') end file.write("ActiveRecord::Base.connection.execute 'INSERT INTO #{table} (#{colArr.join(",")}) VALUES (#{valArr.join(",")})'\n") end end end table names fixed in load_probe_configurations task # # adapted from: # http://www.samsaffron.com/archive/2008/02/02/Redo+your+migrations+in+Rails+and+keep+your+data # NOTE: 09-26-2009 knowuh: these migrations do not seem to work with models which have our scoped name-spaces. # def username(enviro) dbconfig = YAML::load(File.open('config/database.yml')) dbconfig[enviro]["username"] end def password(enviro) dbconfig = YAML::load(File.open('config/database.yml')) dbconfig[enviro]["password"] end def database(enviro) dbconfig = YAML::load(File.open('config/database.yml')) dbconfig[enviro]["database"] end # something like this will ONLY WORKO ON MYSQL! def clone_production %w|test development|.each do |enviro| puts "trying with environment #{enviro}" %x[ mysqldump --add-drop-table -u #{username(enviro)} -p#{password(enviro)} #{database(enviro)} | mysql -u #{username('production')} -p#{password('production')} #{database('production')} ] end end def interesting_tables tables = ActiveRecord::Base.connection.tables.sort tables.reject! do |tbl| %w{schema_migrations sessions roles_users admin_projects}.include?(tbl) end tables end namespace :db do desc "clone the production db to development and testing (MYSQL ONLY!)" task :clone do clone_production end namespace :backup do desc "Reload the database and rerun migrations" task :redo do Rake::Task['db:backup:write'].invoke Rake::Task['db:reset'].invoke Rake::Task['db:backup:read'].invoke end desc "Saves the db to yaml fixures in config/db/backup." task :save => :environment do dir = RAILS_ROOT + '/config/db_backup' FileUtils.mkdir_p(dir) FileUtils.chdir(dir) do interesting_tables.each do |tbl| klass = tbl.classify.constantize File.open("#{tbl}.yaml", 'w') do |f| attributes = klass.find(:all).collect { |m| m.attributes } f.write YAML.dump(attributes) end end end end desc "Loads the db from yaml fixures in config/db/backup" task :load => [:environment] do dir = RAILS_ROOT + '/config/db_backup' FileUtils.chdir(dir) do interesting_tables.each do |tbl| ActiveRecord::Base.transaction do begin klass = tbl.classify.constantize klass.destroy_all klass.reset_column_information puts "Loading #{tbl}..." table_path = "#{tbl}.yaml" YAML.load_file(table_path).each do |fixture| data = {} klass.columns.each do |c| # filter out missing columns data[c.name] = fixture[c.name] if fixture[c.name] end ActiveRecord::Base.connection.execute "INSERT INTO #{tbl} (#{data.keys.map{|kk| "#{tbl}.#{kk}"}.join(",")}) VALUES (#{data.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert' end rescue puts "failed to load table #{tbl}" end end end end end desc "Save the interface/probe configuration data to yaml fixtures in config/probe_configurations." task :save_probe_configurations => :environment do dir = RAILS_ROOT + '/config/probe_configurations' FileUtils.chdir(dir) do tables = %w{probe_device_configs probe_data_filters probe_vendor_interfaces probe_physical_units probe_calibrations probe_probe_types} tables.each do |tbl| puts "writing #{dir}/#{tbl}.yaml" File.open("#{tbl}.yaml", 'w') do |f| attributes = tbl.classify.constantize.find(:all).collect { |m| m.attributes } f.write YAML.dump(attributes) end end end end desc "Load just the probe configurations from yaml fixtures in config/probe_configurations." task :load_probe_configurations => :environment do dir = RAILS_ROOT + '/config/probe_configurations' user_id = User.site_admin.id FileUtils.chdir(dir) do tables = %w{probe_device_configs probe_data_filters probe_vendor_interfaces probe_physical_units probe_calibrations probe_probe_types} tables.each do |tbl| ActiveRecord::Base.transaction do begin klass = tbl.classify.constantize klass.destroy_all klass.reset_column_information puts "Loading #{tbl}..." table_path = "#{tbl}.yaml" YAML.load_file(table_path).each do |fixture| data = {} klass.columns.each do |c| # filter out missing columns data[c.name] = fixture[c.name] if fixture[c.name] # if there is a field named user_id set it's value to the id for the rites site admin if c.name == 'user_id' data[c.name] = user_id end end ActiveRecord::Base.connection.execute "INSERT INTO #{tbl} (#{data.keys.map{|kk| "#{tbl}.#{kk}"}.join(",")}) VALUES (#{data.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert' end rescue StandardError => e puts e puts "failed to load table #{tbl}" end end end end end desc "Dump just the Factory Girl factory definitions from the current db" task :dump_defs_to_factory_girl => :environment do @just_factories = true Rake::Task['db:backup:dump_to_factory_girl'].invoke end desc "Dump the db to a rough Factory Girl format" task :dump_to_factory_girl => :environment do @skip_attrs = ["id", "created_at", "updated_at", "uuid"] @namespaced = {"maven_jnlp_" => "MavenJnlp::", "admin_" => "Admin::", "dataservice_" => "Dataservice::", "otrunk_example_" => "OtrunkExample::", "portal_" => "Portal::"} # @non_rich_joins = ["jars_versioned_jnlps","portal_courses_grade_levels","portal_grade_levels_teachers"] ActiveRecord::Base.connection.tables.each do |table| print "Dumping #{table}... " tablename = table.singularize classname = "" @namespaced.each do |k,v| if table =~ /^#{k}/ classname = ", :class => #{v}#{tablename.sub(/^#{k}/,'').classify}" end end cols = [] ActiveRecord::Base.connection.columns(table).each do |col| cols << col.name end f = nil if cols.include?("id") f = File.open("#{RAILS_ROOT}/features/factories/#{table}.rb", "w") f.write "Factory.define :#{tablename}#{classname} do |f|\n" f.write "end\n\n" else if @just_factories # no op else f = File.open("#{RAILS_ROOT}/features/factories/#{table}.rb", "w") f.write "# #{table}: This is a non-rich join table\n\n" end end objs = ActiveRecord::Base.connection.execute "SELECT * from #{table}" objs.each do |o| if ! @just_factories if cols.include?("id") write_factory(f,tablename,cols,o) else write_joins(f,table,cols,o) end end end if f f.flush f.close end print " done.\n" end end def write_factory(file, table, cols, vals) tvals = [cols,vals].transpose out_vals = [] tvals.each do |val| next if @skip_attrs.include?(val[0]) out_vals << ":#{val[0]} => '#{val[1].to_s.sub(/'/,'\\\'')}'" end file.write("Factory.create(:#{table},{\n " + out_vals.join(",\n ") + "\n})\n") end def write_joins(file, table, cols, vals) return if @just_factories tvals = [cols,vals].transpose colArr = [] valArr = [] tvals.each do |val| next if @skip_attrs.include?(val[0]) colArr << val[0] valArr << val[1].to_s.sub(/'/,'\\\'') end file.write("ActiveRecord::Base.connection.execute 'INSERT INTO #{table} (#{colArr.join(",")}) VALUES (#{valArr.join(",")})'\n") end end end
# desc "Explaining what the task does" # task :obvious_data do # # Task goes here # end Delete unused rake task file
namespace :mailer task send_status_emails: :environment do summary_stats = {} summary_stats[:week_start] = Time.zone.today - 7.days summary_stats[:week_end] = Time.zone.today summary_stats[:weeks_comments] = TaskComment.where("created_at >= :start AND created_at < :end", start: summary_stats[:week_start], end: summary_stats[:week_end]).count summary_stats[:weeks_engagements] = TaskEngagement.where("engagement_time >= :start AND engagement_time < :end", start: summary_stats[:week_start], end: summary_stats[:week_end]).count Unit.where(active: true).each do |unit| next unless summary_stats[:week_start] > unit.start_date && summary_stats[:week_start] < unit.end_date unit.send_weekly_status_emails(summary_stats) end end end FIX: Missing do in mailer action namespace :mailer do task send_status_emails: :environment do summary_stats = {} summary_stats[:week_start] = Time.zone.today - 7.days summary_stats[:week_end] = Time.zone.today summary_stats[:weeks_comments] = TaskComment.where("created_at >= :start AND created_at < :end", start: summary_stats[:week_start], end: summary_stats[:week_end]).count summary_stats[:weeks_engagements] = TaskEngagement.where("engagement_time >= :start AND engagement_time < :end", start: summary_stats[:week_start], end: summary_stats[:week_end]).count Unit.where(active: true).each do |unit| next unless summary_stats[:week_start] > unit.start_date && summary_stats[:week_start] < unit.end_date unit.send_weekly_status_emails(summary_stats) end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "iron_worker_ng" s.version = "0.7.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Andrew Kirilenko", "Iron.io, Inc"] s.date = "2012-06-26" s.description = "New generation ruby client for IronWorker" s.email = "info@iron.io" s.executables = ["iron_worker"] s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ "LICENSE", "README.md", "VERSION", "bin/iron_worker", "lib/3rdparty/hashie/indifferent_access.rb", "lib/3rdparty/hashie/merge_initializer.rb", "lib/iron_worker_ng.rb", "lib/iron_worker_ng/api_client.rb", "lib/iron_worker_ng/client.rb", "lib/iron_worker_ng/code/base.rb", "lib/iron_worker_ng/code/binary.rb", "lib/iron_worker_ng/code/builder.rb", "lib/iron_worker_ng/code/creator.rb", "lib/iron_worker_ng/code/initializer.rb", "lib/iron_worker_ng/code/java.rb", "lib/iron_worker_ng/code/node.rb", "lib/iron_worker_ng/code/ruby.rb", "lib/iron_worker_ng/feature/base.rb", "lib/iron_worker_ng/feature/binary/merge_exec.rb", "lib/iron_worker_ng/feature/common/merge_dir.rb", "lib/iron_worker_ng/feature/common/merge_file.rb", "lib/iron_worker_ng/feature/java/merge_exec.rb", "lib/iron_worker_ng/feature/java/merge_jar.rb", "lib/iron_worker_ng/feature/node/merge_exec.rb", "lib/iron_worker_ng/feature/ruby/merge_exec.rb", "lib/iron_worker_ng/feature/ruby/merge_gem.rb", "lib/iron_worker_ng/feature/ruby/merge_gemfile.rb", "lib/iron_worker_ng/fetcher.rb", "lib/iron_worker_ng/version.rb", "ng_tests_worker.rb", "remote_test.rb" ] s.homepage = "https://github.com/iron-io/iron_worker_ruby_ng" s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "New generation ruby client for IronWorker" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<iron_core>, [">= 0.1.4"]) s.add_runtime_dependency(%q<zip>, [">= 0"]) s.add_runtime_dependency(%q<bundler>, ["> 1.0.0"]) s.add_development_dependency(%q<rake>, [">= 0"]) s.add_development_dependency(%q<jeweler2>, [">= 0"]) else s.add_dependency(%q<iron_core>, [">= 0.1.4"]) s.add_dependency(%q<zip>, [">= 0"]) s.add_dependency(%q<bundler>, ["> 1.0.0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<jeweler2>, [">= 0"]) end else s.add_dependency(%q<iron_core>, [">= 0.1.4"]) s.add_dependency(%q<zip>, [">= 0"]) s.add_dependency(%q<bundler>, ["> 1.0.0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<jeweler2>, [">= 0"]) end end Regenerate gemspec for version 0.8.0 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "iron_worker_ng" s.version = "0.8.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Andrew Kirilenko", "Iron.io, Inc"] s.date = "2012-07-10" s.description = "New generation ruby client for IronWorker" s.email = "info@iron.io" s.executables = ["iron_worker"] s.extra_rdoc_files = [ "LICENSE", "README.md" ] s.files = [ "LICENSE", "README.md", "VERSION", "bin/iron_worker", "lib/3rdparty/hashie/indifferent_access.rb", "lib/3rdparty/hashie/merge_initializer.rb", "lib/iron_worker_ng.rb", "lib/iron_worker_ng/api_client.rb", "lib/iron_worker_ng/client.rb", "lib/iron_worker_ng/code/base.rb", "lib/iron_worker_ng/code/binary.rb", "lib/iron_worker_ng/code/builder.rb", "lib/iron_worker_ng/code/java.rb", "lib/iron_worker_ng/code/mono.rb", "lib/iron_worker_ng/code/node.rb", "lib/iron_worker_ng/code/php.rb", "lib/iron_worker_ng/code/python.rb", "lib/iron_worker_ng/code/ruby.rb", "lib/iron_worker_ng/code/runtime/binary.rb", "lib/iron_worker_ng/code/runtime/java.rb", "lib/iron_worker_ng/code/runtime/mono.rb", "lib/iron_worker_ng/code/runtime/node.rb", "lib/iron_worker_ng/code/runtime/php.rb", "lib/iron_worker_ng/code/runtime/python.rb", "lib/iron_worker_ng/code/runtime/ruby.rb", "lib/iron_worker_ng/feature/base.rb", "lib/iron_worker_ng/feature/binary/merge_exec.rb", "lib/iron_worker_ng/feature/common/merge_dir.rb", "lib/iron_worker_ng/feature/common/merge_file.rb", "lib/iron_worker_ng/feature/java/merge_exec.rb", "lib/iron_worker_ng/feature/java/merge_jar.rb", "lib/iron_worker_ng/feature/mono/merge_exec.rb", "lib/iron_worker_ng/feature/node/merge_exec.rb", "lib/iron_worker_ng/feature/php/merge_exec.rb", "lib/iron_worker_ng/feature/python/merge_exec.rb", "lib/iron_worker_ng/feature/ruby/merge_exec.rb", "lib/iron_worker_ng/feature/ruby/merge_gem.rb", "lib/iron_worker_ng/feature/ruby/merge_gemfile.rb", "lib/iron_worker_ng/fetcher.rb", "lib/iron_worker_ng/version.rb", "ng_tests_worker.rb", "remote_test.rb" ] s.homepage = "https://github.com/iron-io/iron_worker_ruby_ng" s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "New generation ruby client for IronWorker" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<iron_core>, [">= 0.2.0"]) s.add_runtime_dependency(%q<zip>, [">= 0"]) s.add_runtime_dependency(%q<bundler>, ["> 1.0.0"]) s.add_development_dependency(%q<rake>, [">= 0"]) s.add_development_dependency(%q<jeweler2>, [">= 0"]) else s.add_dependency(%q<iron_core>, [">= 0.2.0"]) s.add_dependency(%q<zip>, [">= 0"]) s.add_dependency(%q<bundler>, ["> 1.0.0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<jeweler2>, [">= 0"]) end else s.add_dependency(%q<iron_core>, [">= 0.2.0"]) s.add_dependency(%q<zip>, [">= 0"]) s.add_dependency(%q<bundler>, ["> 1.0.0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<jeweler2>, [">= 0"]) end end
################################################################################ # Start cloud functions ################################################################################ # Starting function for leader node. def leader_start(cloud_type, vm_ips, vm_ip_roles, vm_img_roles, pm_up, monitor_function) # We are the leader puts "#{MY_IP} is the leader" # Check wether virtual machines are alive or not alive = {} vm_ips.each do |vm| alive[vm] = false end puts "Checking whether virtual machines are alive..." vm_ips.each do |vm| result = `#{PING} #{vm}` if $?.exitstatus == 0 debug "[DBG] #{vm} is up" alive[vm] = true else debug "[DBG] #{vm} is down" puts "#{vm} is down" end end # Monitor the alive machines. Start and configure the dead ones. deads = false vm_ips.each do |vm| if alive[vm] # If they are alive, monitor them puts "Monitoring #{vm}..." monitor_vm(vm, vm_ip_roles, monitor_function) puts "...Monitored" else # If they are not alive, start and configure them puts "Starting #{vm}..." start_vm(vm, vm_ip_roles, vm_img_roles, pm_up) puts "...Started" deads = true end end # Wait for all machines to be started unless deads # If not already started, start the cloud unless File.exists?("/tmp/cloud-#{resource[:name]}") # Copy important files to all machines puts "Copying important files to all virtual machines" copy_cloud_files(vm_ips, cloud_type) # TODO Move it to monitor and call it each time for one vm? # Start the cloud if start_cloud(vm_ips, vm_ip_roles) # Make cloud nodes manage themselves #auto_manage(cloud_type) # Only if cloud was started properly FIXME Uncomment after tests # Create file cloud_file = File.open("/tmp/cloud-#{resource[:name]}", 'w') cloud_file.puts(resource[:name]) cloud_file.close puts "===================" puts "== Cloud started ==" puts "===================" else puts "Impossible to start cloud" end end # unless File end # unless deads end # Starting function for common (non-leader) nodes. def common_start # We are not the leader or we have not received our ID yet puts "#{MY_IP} is not the leader" my_id = CloudLeader.get_id() if my_id == -1 # If we have not received our ID, let's assume we will be the leader CloudLeader.set_id(0) CloudLeader.set_leader(0) puts "#{MY_IP} will be the leader" # Create your ssh key CloudSSH.generate_ssh_key() else # If we have received our ID, try to become leader puts "Trying to become leader..." # Get all machines' IDs mcc = MCollectiveLeaderClient.new("leader") ids = mcc.ask_id() # See if some other machine is leader exists_leader = false ids.each do |id| if id < my_id exists_leader = true break end end # If there is no leader, we will be the new leader if !exists_leader mcc.new_leader(my_id.to_s()) puts "...#{MY_IP} will be leader" # Create your ssh key CloudSSH.generate_ssh_key() else puts "...Some other machine is/should be leader" end mcc.disconnect return end end # Starting function for nodes which do not belong to the cloud. def not_cloud_start(cloud_type, vm_ips, vm_ip_roles, vm_img_roles, pm_up) # Try to find one virtual machine that is already running alive = false vm_leader = "" vm_ips.each do |vm| result = `#{PING} #{vm}` if $?.exitstatus == 0 puts "#{vm} is up" alive = true vm_leader = vm break end end if !alive puts "All virtual machines are stopped" puts "Starting one of them..." # Start one of the virtual machines vm = vm_ips[rand(vm_ips.count)] # Choose one randomly puts "Starting #{vm} ..." start_vm(vm, vm_ip_roles, vm_img_roles, pm_up) # That virtual machine will be the "leader" (actually the chosen one) vm_leader = vm # Copy important files to it #copy_cloud_files(vm_leader, cloud_type) puts "#{vm_leader} is being started" puts "Once started, do 'puppet apply manifest.pp' on #{vm_leader}" else puts "#{vm_leader} is already running" puts "Do 'puppet apply manifest.pp' on #{vm_leader}" end end def leader_monitoring(monitor_function) puts "#{MY_IP} is the leader" # Do monitoring deads = [] vm_ips, vm_ip_roles, vm_img_roles = obtain_vm_data() vm_ips.each do |vm| puts "Monitoring #{vm}..." unless monitor_vm(vm, vm_ip_roles, monitor_function) deads << vm end puts "...Monitored" end # Check pool of physical machines pm_up, pm_down = check_pool() if deads.count == 0 puts "==========================" puts "== Cloud up and running ==" puts "==========================" else # Raise again the dead machines deads.each do |vm| start_vm(vm, vm_ip_roles, vm_img_roles, pm_up) end end end ################################################################################ # Stop cloud functions ################################################################################ # Shuts down virtual machines. def shutdown_vms # Get pool of physical machines pms = resource[:pool] # Shut down virtual machines pms.each do |pm| pm_user = resource[:pm_user] pm_password = resource[:pm_password] # Copy ssh key to physical machine puts "Copying ssh key to physical machine" out, success = CloudSSH.copy_ssh_key(pm_user, pm, pm_password) # Bring the defined domains file from the physical machine to this one out, success = CloudSSH.get_remote(DOMAINS_FILE, pm_user, pm, DOMAINS_FILE) if success puts "#{DOMAINS_FILE} exists in #{pm}" # Open files defined_domains = File.open(DOMAINS_FILE, 'r') # Stop nodes puts "Shutting down domains" defined_domains.each_line do |domain| domain.chomp! command = "#{VIRSH_CONNECT} shutdown #{domain}" out, success = CloudSSH.execute_remote(command, pm_user, pm) if success debug "[DBG] #{domain} was shutdown" else debug "[DBG] #{domain} impossible to shutdown" err "#{domain} impossible to shutdown" end end # Undefine local domains puts "Undefining domains" defined_domains.rewind defined_domains.each_line do |domain| domain.chomp! command = "#{VIRSH_CONNECT} undefine #{domain}" out, success = CloudSSH.execute_remote(command, pm_user, pm) if success debug "[DBG] #{domain} was undefined" else debug "[DBG] #{domain} impossible to undefine" err "#{domain} impossible to undefine" end end # Delete the defined domains file on the physical machine puts "Deleting defined domains file" command = "rm -rf #{DOMAINS_FILE}" out, success = CloudSSH.execute_remote(command, pm_user, pm) # Delete all the domain files on the physical machine. Check how the # name is defined on 'start_vm' function. puts "Deleting domain files" domain_files = "cloud-%s-*.xml" % [resource[:name]] command = "rm /tmp/#{domain_files}" out, success = CloudSSH.execute_remote(command, pm_user, pm) else # Some physical machines might not have any virtual machine defined. # For instance, if they were already defined and running when we # started the cloud. puts "No #{DOMAINS_FILE} file found in #{pm}" end end # pms.each end # Deletes cloud files on all machines. def delete_files() puts "Deleting cloud files on all machines..." # Create an MCollective client so that we avoid errors that appear # when you create more than one client in a short time mcc = MCollectiveFilesClient.new("files") # Delete leader, id, last_id and last_mac files on all machines (leader included) mcc.delete_file(CloudLeader::LEADER_FILE) # Leader ID mcc.delete_file(CloudLeader::ID_FILE) # ID mcc.delete_file(CloudLeader::LAST_ID_FILE) # Last ID mcc.delete_file(LAST_MAC_FILE) # Last MAC address mcc.disconnect # Now it can be disconnected # Delete rest of regular files on leader machine files = [DOMAINS_FILE, # Domains file "/tmp/cloud-#{resource[:name]}"] # Cloud file files.each do |file| if File.exists?(file) File.delete(file) else puts "File #{file} does not exist" end end end ################################################################################ # Auxiliar functions ################################################################################ # Checks the pool of physical machines are OK. def check_pool machines_up = [] machines_down = [] machines = resource[:pool] machines.each do |machine| result = `#{PING} #{machine}` if $?.exitstatus == 0 debug "[DBG] #{machine} (PM) is up" machines_up << machine else debug "[DBG] #{machine} (PM) is down" machines_down << machine end end return machines_up, machines_down end # Obtains the virtual machine's data #def obtain_vm_data(ip_function, img_function) # # vm_ips = [] # vm_ip_roles = [] # vm_img_roles = [] # puts "Obtaining virtual machines' data" # vm_ips, vm_ip_roles = ip_function.call(resource[:ip_file]) # vm_img_roles = img_function.call(resource[:img_file]) # return vm_ips, vm_ip_roles, vm_img_roles # #end # Checks if this node is the leader def leader? my_id = CloudLeader.get_id() leader = CloudLeader.get_leader() return my_id == leader && my_id != -1 end # Monitors a virtual machine. # Returns false if the machine is not alive. def monitor_vm(vm, ip_roles, monitor_function) # Check if it is alive alive = CloudMonitor.ping(vm) unless alive err "#{vm} is not alive. Impossible to monitor" # If it is not alive there is no point in continuing return false end # Send it your ssh key # Your key was created when you turned into leader puts "Sending ssh key to #{vm}" password = resource[:root_password] out, success = CloudSSH.copy_ssh_key("root", vm, password) if success puts "ssh key sent" else err "ssh key impossible to send" end # Check if MCollective is installed and configured mcollective_installed = CloudMonitor.mcollective_installed(vm) unless mcollective_installed err "MCollective is not installed on #{vm}" end # Make sure MCollective is running. # We need this to ensure the leader election, so ensuring MCollective # is running can not be left to Puppet in their local manifest. It must be # done explicitly here and now. mcollective_running = CloudMonitor.mcollective_running(vm) unless mcollective_running err "MCollective is not running on #{vm}" end # A node may have different roles vm_roles = get_vm_roles(ip_roles, vm) # Check if they have their ID # If they are running, but they do not have their ID: # - Set their ID before they can become another leader. # - Set also the leader's ID. success = CloudLeader.vm_check_id(vm) unless success # Set their ID (based on the last ID we defined) id = CloudLeader.get_last_id() id += 1 CloudLeader.vm_set_id(vm, id) CloudLeader.set_last_id(id) # Set the leader's ID leader = CloudLeader.get_leader() CloudLeader.vm_set_leader(vm, leader) # Send the last ID to all nodes mcc = MCollectiveFilesClient.new("files") mcc.create_file(CloudLeader::LAST_ID_FILE, id.to_s) #mcc.disconnect end # TODO Copy cloud files each time a machine is monitored? # TODO Copy files no matter what or check first if they have them? # Use copy_cloud_files if we copy no matter what. Modify it if we check # We should copy no matter what in case they have changed # Depending on the type of cloud we will have to monitor different components. # Also, take into account that one node can perform more than one role. print "#{vm} will perform the roles: " p vm_roles vm_roles.each do |role| monitor_function.call(vm, role) end return true end # Copies important files to all machines inside <ips>. def copy_cloud_files(ips, cloud_type) # Use MCollective? # - Without MCollective we are able to send it to both one machine or multiple # machines without changing anything, so not really. ips.each do |vm| if vm != MY_IP # Cloud manifest file = "init-#{cloud_type}.pp" path = "/etc/puppet/modules/#{cloud_type}/manifests/#{file}" out, success = CloudSSH.copy_remote(path, vm, path) unless success err "Impossible to copy #{file} to #{vm}" end # Cloud description (IPs YAML file) TODO Check how to do this #out, success = CloudSSH.copy_remote(resource[:ip_file], vm, resource[:ip_file]) #unless success # err "Impossible to copy #{resource[:ip_file]} to #{vm}" #end # Cloud roles (Image disks YAML file) #out, success = CloudSSH.copy_remote(resource[:img_file], vm, resource[:img_file]) #unless success # err "Impossible to copy #{resource[:img_file]} to #{vm}" #end end end end # Makes the cloud auto-manageable through crontab files. def auto_manage(cloud_type) cron_file = "crontab-#{cloud_type}" path = "/etc/puppet/modules/#{cloud_type}/files/cron/#{cron_file}" if File.exists?(path) file = File.open(path, 'r') line = file.read().chomp() file.close # Add the 'puppet apply manifest.pp' line to the crontab file mcc = MCollectiveCronClient.new("cronos") mcc.add_line(CRON_FILE, line) mcc.disconnect else err "Impossible to find cron file at #{path}" end end [dev] genericp_main refactored ################################################################################ # Start cloud functions ################################################################################ # Starting function for leader node. def leader_start(cloud_type, vm_ips, vm_ip_roles, vm_img_roles, pm_up, monitor_function) # We are the leader puts "#{MY_IP} is the leader" # Check wether virtual machines are alive or not alive = {} vm_ips.each do |vm| alive[vm] = false end puts "Checking whether virtual machines are alive..." vm_ips.each do |vm| result = `#{PING} #{vm}` if $?.exitstatus == 0 debug "[DBG] #{vm} is up" alive[vm] = true else debug "[DBG] #{vm} is down" puts "#{vm} is down" end end # Monitor the alive machines. Start and configure the dead ones. deads = false vm_ips.each do |vm| if alive[vm] # If they are alive, monitor them puts "Monitoring #{vm}..." monitor_vm(vm, vm_ip_roles, monitor_function) puts "...Monitored" else # If they are not alive, start and configure them puts "Starting #{vm}..." start_vm(vm, vm_ip_roles, vm_img_roles, pm_up) puts "...Started" deads = true end end # Wait for all machines to be started unless deads # If not already started, start the cloud unless File.exists?("/tmp/cloud-#{resource[:name]}") # Copy important files to all machines puts "Copying important files to all virtual machines" copy_cloud_files(vm_ips, cloud_type) # TODO Move it to monitor and call it each time for one vm? # Start the cloud if start_cloud(vm_ips, vm_ip_roles) # Make cloud nodes manage themselves #auto_manage(cloud_type) # Only if cloud was started properly FIXME Uncomment after tests # Create file cloud_file = File.open("/tmp/cloud-#{resource[:name]}", 'w') cloud_file.puts(resource[:name]) cloud_file.close puts "===================" puts "== Cloud started ==" puts "===================" else puts "Impossible to start cloud" end end # unless File end # unless deads end # Starting function for common (non-leader) nodes. def common_start() # We are not the leader or we have not received our ID yet puts "#{MY_IP} is not the leader" my_id = CloudLeader.get_id() if my_id == -1 # If we have not received our ID, let's assume we will be the leader CloudLeader.set_id(0) CloudLeader.set_leader(0) puts "#{MY_IP} will be the leader" # Create your ssh key CloudSSH.generate_ssh_key() else # If we have received our ID, try to become leader puts "Trying to become leader..." # Get all machines' IDs mcc = MCollectiveLeaderClient.new("leader") ids = mcc.ask_id() # See if some other machine is leader exists_leader = false ids.each do |id| if id < my_id exists_leader = true break end end # If there is no leader, we will be the new leader if !exists_leader mcc.new_leader(my_id.to_s()) puts "...#{MY_IP} will be leader" # Create your ssh key CloudSSH.generate_ssh_key() else puts "...Some other machine is/should be leader" end mcc.disconnect return end end # Starting function for nodes which do not belong to the cloud. def not_cloud_start(cloud_type, vm_ips, vm_ip_roles, vm_img_roles, pm_up) # Try to find one virtual machine that is already running alive = false vm_leader = "" vm_ips.each do |vm| result = `#{PING} #{vm}` if $?.exitstatus == 0 puts "#{vm} is up" alive = true vm_leader = vm break end end if !alive puts "All virtual machines are stopped" puts "Starting one of them..." # Start one of the virtual machines vm = vm_ips[rand(vm_ips.count)] # Choose one randomly puts "Starting #{vm} ..." start_vm(vm, vm_ip_roles, vm_img_roles, pm_up) # That virtual machine will be the "leader" (actually the chosen one) vm_leader = vm # Copy important files to it #copy_cloud_files(vm_leader, cloud_type) puts "#{vm_leader} is being started" puts "Once started, do 'puppet apply manifest.pp' on #{vm_leader}" else puts "#{vm_leader} is already running" puts "Do 'puppet apply manifest.pp' on #{vm_leader}" end end def leader_monitoring(monitor_function) puts "#{MY_IP} is the leader" # Do monitoring deads = [] vm_ips, vm_ip_roles, vm_img_roles = obtain_vm_data() vm_ips.each do |vm| puts "Monitoring #{vm}..." unless monitor_vm(vm, vm_ip_roles, monitor_function) deads << vm end puts "...Monitored" end # Check pool of physical machines pm_up, pm_down = check_pool() if deads.count == 0 puts "==========================" puts "== Cloud up and running ==" puts "==========================" else # Raise again the dead machines deads.each do |vm| start_vm(vm, vm_ip_roles, vm_img_roles, pm_up) end end end ################################################################################ # Stop cloud functions ################################################################################ # Shuts down virtual machines. def shutdown_vms() # Get pool of physical machines pms = resource[:pool] # Shut down virtual machines pms.each do |pm| pm_user = resource[:pm_user] pm_password = resource[:pm_password] # Copy ssh key to physical machine puts "Copying ssh key to physical machine" out, success = CloudSSH.copy_ssh_key(pm_user, pm, pm_password) # Bring the defined domains file from the physical machine to this one out, success = CloudSSH.get_remote(DOMAINS_FILE, pm_user, pm, DOMAINS_FILE) if success puts "#{DOMAINS_FILE} exists in #{pm}" # Open files defined_domains = File.open(DOMAINS_FILE, 'r') # Stop nodes puts "Shutting down domains" shutdown_domains(defined_domains, pm_user, pm) # Undefine local domains puts "Undefining domains" defined_domains.rewind undefine_domains(defined_domains, pm_user, pm) # Delete the defined domains file on the physical machine puts "Deleting defined domains file" command = "rm -rf #{DOMAINS_FILE}" out, success = CloudSSH.execute_remote(command, pm_user, pm) # Delete all the domain files on the physical machine. Check how the # name is defined on 'start_vm' function. puts "Deleting domain files" domain_files = "cloud-%s-*.xml" % [resource[:name]] command = "rm /tmp/#{domain_files}" out, success = CloudSSH.execute_remote(command, pm_user, pm) else # Some physical machines might not have any virtual machine defined. # For instance, no virtual machine will be defined if they were already # defined and running when we started the cloud. puts "No #{DOMAINS_FILE} file found in #{pm}" end end # pms.each end # Shuts down KVM domains. def shutdown_domains(defined_domains, pm_user, pm) defined_domains.each_line do |domain| domain.chomp! command = "#{VIRSH_CONNECT} shutdown #{domain}" out, success = CloudSSH.execute_remote(command, pm_user, pm) if success debug "[DBG] #{domain} was shutdown" else debug "[DBG] #{domain} impossible to shutdown" err "#{domain} impossible to shutdown" end end end # Undefines KVM domains. def undefine_domains(defined_domains, pm_user, pm) defined_domains.each_line do |domain| domain.chomp! command = "#{VIRSH_CONNECT} undefine #{domain}" out, success = CloudSSH.execute_remote(command, pm_user, pm) if success debug "[DBG] #{domain} was undefined" else debug "[DBG] #{domain} impossible to undefine" err "#{domain} impossible to undefine" end end end # Deletes cloud files on all machines. def delete_files() puts "Deleting cloud files on all machines..." # Create an MCollective client so that we avoid errors that appear # when you create more than one client in a short time mcc = MCollectiveFilesClient.new("files") # Delete leader, id, last_id and last_mac files on all machines (leader included) mcc.delete_file(CloudLeader::LEADER_FILE) # Leader ID mcc.delete_file(CloudLeader::ID_FILE) # ID mcc.delete_file(CloudLeader::LAST_ID_FILE) # Last ID mcc.delete_file(LAST_MAC_FILE) # Last MAC address mcc.disconnect # Now it can be disconnected # Delete rest of regular files on leader machine files = [DOMAINS_FILE, # Domains file "/tmp/cloud-#{resource[:name]}"] # Cloud file files.each do |file| if File.exists?(file) File.delete(file) else puts "File #{file} does not exist" end end end ################################################################################ # Auxiliar functions ################################################################################ # Checks the pool of physical machines are OK. def check_pool() machines_up = [] machines_down = [] machines = resource[:pool] machines.each do |machine| result = `#{PING} #{machine}` if $?.exitstatus == 0 debug "[DBG] #{machine} (PM) is up" machines_up << machine else debug "[DBG] #{machine} (PM) is down" machines_down << machine end end return machines_up, machines_down end # Obtains the virtual machine's data #def obtain_vm_data(ip_function, img_function) # # vm_ips = [] # vm_ip_roles = [] # vm_img_roles = [] # puts "Obtaining virtual machines' data" # vm_ips, vm_ip_roles = ip_function.call(resource[:ip_file]) # vm_img_roles = img_function.call(resource[:img_file]) # return vm_ips, vm_ip_roles, vm_img_roles # #end # Checks if this node is the leader def leader?() my_id = CloudLeader.get_id() leader = CloudLeader.get_leader() return my_id == leader && my_id != -1 end # Monitors a virtual machine. # Returns false if the machine is not alive. def monitor_vm(vm, ip_roles, monitor_function) # Check if it is alive alive = CloudMonitor.ping(vm) unless alive err "#{vm} is not alive. Impossible to monitor" # If it is not alive there is no point in continuing return false end # Send it your ssh key # Your key was created when you turned into leader puts "Sending ssh key to #{vm}" password = resource[:root_password] out, success = CloudSSH.copy_ssh_key("root", vm, password) if success puts "ssh key sent" else err "ssh key impossible to send" end # Check if MCollective is installed and configured mcollective_installed = CloudMonitor.mcollective_installed(vm) unless mcollective_installed err "MCollective is not installed on #{vm}" end # Make sure MCollective is running. # We need this to ensure the leader election, so ensuring MCollective # is running can not be left to Puppet in their local manifest. It must be # done explicitly here and now. mcollective_running = CloudMonitor.mcollective_running(vm) unless mcollective_running err "MCollective is not running on #{vm}" end # A node may have different roles vm_roles = get_vm_roles(ip_roles, vm) # Check if they have their ID # If they are running, but they do not have their ID: # - Set their ID before they can become another leader. # - Set also the leader's ID. success = CloudLeader.vm_check_id(vm) unless success # Set their ID (based on the last ID we defined) id = CloudLeader.get_last_id() id += 1 CloudLeader.vm_set_id(vm, id) CloudLeader.set_last_id(id) # Set the leader's ID leader = CloudLeader.get_leader() CloudLeader.vm_set_leader(vm, leader) # Send the last ID to all nodes mcc = MCollectiveFilesClient.new("files") mcc.create_file(CloudLeader::LAST_ID_FILE, id.to_s) #mcc.disconnect end # TODO Copy cloud files each time a machine is monitored? # TODO Copy files no matter what or check first if they have them? # Use copy_cloud_files if we copy no matter what. Modify it if we check # We should copy no matter what in case they have changed # Depending on the type of cloud we will have to monitor different components. # Also, take into account that one node can perform more than one role. print "#{vm} will perform the roles: " p vm_roles vm_roles.each do |role| monitor_function.call(vm, role) end return true end # Copies important files to all machines inside <ips>. def copy_cloud_files(ips, cloud_type) # Use MCollective? # - Without MCollective we are able to send it to both one machine or multiple # machines without changing anything, so not really. ips.each do |vm| if vm != MY_IP # Cloud manifest file = "init-#{cloud_type}.pp" path = "/etc/puppet/modules/#{cloud_type}/manifests/#{file}" out, success = CloudSSH.copy_remote(path, vm, path) unless success err "Impossible to copy #{file} to #{vm}" end # Cloud description (IPs YAML file) TODO Check how to do this #out, success = CloudSSH.copy_remote(resource[:ip_file], vm, resource[:ip_file]) #unless success # err "Impossible to copy #{resource[:ip_file]} to #{vm}" #end # Cloud roles (Image disks YAML file) #out, success = CloudSSH.copy_remote(resource[:img_file], vm, resource[:img_file]) #unless success # err "Impossible to copy #{resource[:img_file]} to #{vm}" #end end end end # Makes the cloud auto-manageable through crontab files. def auto_manage(cloud_type) cron_file = "crontab-#{cloud_type}" path = "/etc/puppet/modules/#{cloud_type}/files/cron/#{cron_file}" if File.exists?(path) file = File.open(path, 'r') line = file.read().chomp() file.close # Add the 'puppet apply manifest.pp' line to the crontab file mcc = MCollectiveCronClient.new("cronos") mcc.add_line(CRON_FILE, line) mcc.disconnect else err "Impossible to find cron file at #{path}" end end
require 'httpclient' require 'json' require 'optparse' COUNTRIES = { "AF" => "AFGHANISTAN", "AX" => "ÅLAND ISLANDS", "AL" => "ALBANIA", "DZ" => "ALGERIA", "AS" => "AMERICAN SAMOA", "AD" => "ANDORRA", "AO" => "ANGOLA", "AI" => "ANGUILLA", "AQ" => "ANTARCTICA", "AG" => "ANTIGUA AND BARBUDA", "AR" => "ARGENTINA", "AM" => "ARMENIA", "AW" => "ARUBA", "AU" => "AUSTRALIA", "AT" => "AUSTRIA", "AZ" => "AZERBAIJAN", "BS" => "BAHAMAS, THE", "BH" => "BAHRAIN", "BD" => "BANGLADESH", "BB" => "BARBADOS", "BY" => "BELARUS", "BE" => "BELGIUM", "BZ" => "BELIZE", "BJ" => "BENIN", "BM" => "BERMUDA", "BT" => "BHUTAN", "BO" => "BOLIVIA", "BQ" => "BONAIRE", "BA" => "BOSNIA AND HERZEGOVINA", "BW" => "BOTSWANA", "BV" => "BOUVET ISLAND", "BR" => "BRAZIL", "IO" => "BRITISH INDIAN OCEAN TERRITORY", "BN" => "BRUNEI", "BG" => "BULGARIA", "BF" => "BURKINA FASO", "BI" => "BURUNDI", "KH" => "CAMBODIA", "CM" => "CAMEROON", "CA" => "CANADA", "CV" => "CAPE VERDE", "KY" => "CAYMAN ISLANDS", "CF" => "CENTRAL AFRICAN REPUBLIC", "TD" => "CHAD", "CL" => "CHILE", "CN" => "CHINA", "CX" => "CHRISTMAS ISLAND", "CC" => "COCOS ISLANDS", "CO" => "COLOMBIA", "KM" => "COMOROS", "CG" => "CONGO (BRAZZAVILLE)", "CD" => "CONGO (KINSHASA)", "CK" => "COOK ISLANDS", "CR" => "COSTA RICA", "CI" => "CÔTE D'IVOIRE", "HR" => "CROATIA", "CU" => "CUBA", "CW" => "CURAÇAO", "CY" => "CYPRUS", "CZ" => "CZECHIA", "DK" => "DENMARK", "DJ" => "DJIBOUTI", "DM" => "DOMINICA", "DO" => "DOMINICAN REPUBLIC", "EC" => "ECUADOR", "EG" => "EGYPT", "SV" => "EL SALVADOR", "GQ" => "EQUATORIAL GUINEA", "ER" => "ERITREA", "EE" => "ESTONIA", "ET" => "ETHIOPIA", "FK" => "FALKLAND ISLANDS", "FO" => "FAROE ISLANDS", "FJ" => "FIJI", "FI" => "FINLAND", "FR" => "FRANCE", "GF" => "GUIANA", "PF" => "POLYNESIA", "TF" => "FRENCH SOUTHERN TERRITORIES", "GA" => "GABON", "GM" => "GAMBIA, THE", "GE" => "GEORGIA", "DE" => "GERMANY", "GH" => "GHANA", "GI" => "GIBRALTAR", "GR" => "GREECE", "GL" => "GREENLAND", "GD" => "GRENADA", "GP" => "GUADELOUPE", "GU" => "GUAM", "GT" => "GUATEMALA", "GG" => "GUERNSEY", "GN" => "GUINEA", "GW" => "GUINEA-BISSAU", "GY" => "GUYANA", "HT" => "HAITI", "HM" => "HEARD ISLAND AND MCDONALD ISLANDS", "VA" => "HOLY SEE", "HN" => "HONDURAS", "HK" => "HONG KONG", "HU" => "HUNGARY", "IS" => "ICELAND", "IN" => "INDIA", "ID" => "INDONESIA", "IR" => "IRAN", "IQ" => "IRAQ", "IE" => "IRELAND", "IM" => "ISLE OF MAN", "IL" => "ISRAEL", "IT" => "ITALY", "JM" => "JAMAICA", "JP" => "JAPAN", "JE" => "JERSEY", "JO" => "JORDAN", "KZ" => "KAZAKHSTAN", "KE" => "KENYA", "KI" => "KIRIBATI", "KP" => "KOREA, NORTH", "KR" => "KOREA, SOUTH", "KW" => "KUWAIT", "KG" => "KYRGYZSTAN", "LA" => "LAOS", "LV" => "LATVIA", "LB" => "LEBANON", "LS" => "LESOTHO", "LR" => "LIBERIA", "LY" => "LIBYA", "LI" => "LIECHTENSTEIN", "LT" => "LITHUANIA", "LU" => "LUXEMBOURG", "MO" => "MACAO", "MK" => "NORTH MACEDONIA", "MG" => "MADAGASCAR", "MW" => "MALAWI", "MY" => "MALAYSIA", "MV" => "MALDIVES", "ML" => "MALI", "MT" => "MALTA", "MH" => "MARSHALL ISLANDS", "MQ" => "MARTINIQUE", "MR" => "MAURITANIA", "MU" => "MAURITIUS", "YT" => "MAYOTTE", "MX" => "MEXICO", "FM" => "MICRONESIA", "MD" => "MOLDOVA", "MC" => "MONACO", "MN" => "MONGOLIA", "ME" => "MONTENEGRO", "MS" => "MONTSERRAT", "MA" => "MOROCCO", "MZ" => "MOZAMBIQUE", "MM" => "MYANMAR", "NA" => "NAMIBIA", "NR" => "NAURU", "NP" => "NEPAL", "NL" => "NETHERLANDS", "NC" => "NEW CALEDONIA", "NZ" => "NEW ZEALAND", "NI" => "NICARAGUA", "NE" => "NIGER", "NG" => "NIGERIA", "NU" => "NIUE", "NF" => "NORFOLK ISLAND", "MP" => "NORTHERN MARIANA ISLANDS", "NO" => "NORWAY", "OM" => "OMAN", "PK" => "PAKISTAN", "PW" => "PALAU", "PS" => "PALESTINE, STATE OF", "PA" => "PANAMA", "PG" => "PAPUA NEW GUINEA", "PY" => "PARAGUAY", "PE" => "PERU", "PH" => "PHILIPPINES", "PN" => "PITCAIRN", "PL" => "POLAND", "PT" => "PORTUGAL", "PR" => "PUERTO RICO", "QA" => "QATAR", "RE" => "RÉUNION", "RO" => "ROMANIA", "RU" => "RUSSIA", "RW" => "RWANDA", "BL" => "SAINT BARTHÉLEMY", "SH" => "SAINT HELENA", "KN" => "SAINT KITTS AND NEVIS", "LC" => "SAINT LUCIA", "MF" => "SAINT MARTIN", "PM" => "SAINT PIERRE AND MIQUELON", "VC" => "SAINT VINCENT AND THE GRENADINES", "WS" => "SAMOA", "SM" => "SAN MARINO", "ST" => "SAO TOME AND PRINCIPE", "SA" => "SAUDI ARABIA", "SN" => "SENEGAL", "RS" => "SERBIA", "SC" => "SEYCHELLES", "SL" => "SIERRA LEONE", "SG" => "SINGAPORE", "SX" => "SINT MAARTEN", "SK" => "SLOVAKIA", "SI" => "SLOVENIA", "SB" => "SOLOMON ISLANDS", "SO" => "SOMALIA", "ZA" => "SOUTH AFRICA", "GS" => "GEORGIA", "SS" => "SOUTH SUDAN", "ES" => "SPAIN", "LK" => "SRI LANKA", "SD" => "SUDAN", "SR" => "SURINAME", "SJ" => "SVALBARD AND JAN MAYEN", "SZ" => "SWAZILAND", "SE" => "SWEDEN", "CH" => "SWITZERLAND", "SY" => "SYRIA", "TW" => "TAIWAN", "TJ" => "TAJIKISTAN", "TZ" => "TANZANIA", "TH" => "THAILAND", "TL" => "TIMOR-LESTE", "TG" => "TOGO", "TK" => "TOKELAU", "TO" => "TONGA", "TT" => "TRINIDAD AND TOBAGO", "TN" => "TUNISIA", "TR" => "TURKEY", "TM" => "TURKMENISTAN", "TC" => "TURKS AND CAICOS ISLANDS", "TV" => "TUVALU", "UG" => "UGANDA", "UA" => "UKRAINE", "AE" => "UNITED ARAB EMIRATES", "GB" => "UNITED KINGDOM", "UK" => "UNITED KINGDOM", "US" => "US", "UM" => "UNITED STATES MINOR OUTLYING ISLANDS", "UY" => "URUGUAY", "UZ" => "UZBEKISTAN", "VU" => "VANUATU", "VE" => "VENEZUELA", "VN" => "VIETNAM", "VG" => "VIRGIN ISLANDS", "VI" => "VIRGIN ISLANDS", "WF" => "WALLIS AND FUTUNA", "EH" => "WESTERN SAHARA", "YE" => "YEMEN", "ZM" => "ZAMBIA", "ZW" => "ZIMBABWE", } STATES = { 'AK' => 'ALASKA', 'AL' => 'ALABAMA', 'AR' => 'ARKANSAS', 'AS' => 'AMERICAN SAMOA', 'AZ' => 'ARIZONA', 'CA' => 'CALIFORNIA', 'CO' => 'COLORADO', 'CT' => 'CONNECTICUT', 'DC' => 'DISTRICT OF COLUMBIA', 'DE' => 'DELAWARE', 'FL' => 'FLORIDA', 'GA' => 'GEORGIA', 'GA-state' => 'GEORGIA', 'GU' => 'GUAM', 'HI' => 'HAWAII', 'IA' => 'IOWA', 'ID' => 'IDAHO', 'IL' => 'ILLINOIS', 'IN' => 'INDIANA', 'KS' => 'KANSAS', 'KY' => 'KENTUCKY', 'LA' => 'LOUISIANA', 'MA' => 'MASSACHUSETTS', 'MD' => 'MARYLAND', 'ME' => 'MAINE', 'MI' => 'MICHIGAN', 'MN' => 'MINNESOTA', 'MO' => 'MISSOURI', 'MP' => 'NORTHERN MARIANA ISLANDS', 'MS' => 'MISSISSIPPI', 'MT' => 'MONTANA', 'NA' => 'NATIONAL', 'NC' => 'NORTH CAROLINA', 'ND' => 'NORTH DAKOTA', 'NE' => 'NEBRASKA', 'NH' => 'NEW HAMPSHIRE', 'NJ' => 'NEW JERSEY', 'NM' => 'NEW MEXICO', 'NV' => 'NEVADA', 'NY' => 'NEW YORK', 'OH' => 'OHIO', 'OK' => 'OKLAHOMA', 'OR' => 'OREGON', 'PA' => 'PENNSYLVANIA', 'PR' => 'PUERTO RICO', 'RI' => 'RHODE ISLAND', 'SC' => 'SOUTH CAROLINA', 'SD' => 'SOUTH DAKOTA', 'TN' => 'TENNESSEE', 'TX' => 'TEXAS', 'UT' => 'UTAH', 'VA' => 'VIRGINIA', 'VI' => 'VIRGIN ISLANDS', 'VT' => 'VERMONT', 'WA' => 'WASHINGTON', 'WI' => 'WISCONSIN', 'WV' => 'WEST VIRGINIA', 'WY' => 'WYOMING', } class CovidAPI def initialize end def get_global { region: nil, data: format_data(get_data[:features]), } end def get_from_region region country = COUNTRIES.find{ |k, v| [k, v].include? region.upcase } state = STATES.find{ |k, v| [k, v].include? region.upcase } data = get_data[:features].select do |f| search_predicate f, region, country, state end raise "Region #{region} not found" unless data.size > 0 { region: COUNTRIES.fetch(region, STATES.fetch(region, region)), data: format_data(data), } end def format_data data funcs = [ :sum, :sum, :sum, :sum, :max ] data.map do |f| extract_attrib f end.transpose.zip(funcs).map do |zips| zips.first.reduce{ |t, n| [t, n].send zips.last } end end def search_predicate attrib, region, country, state if country (attrib[:attributes][:Country_Region] || "").upcase == country.last elsif state (attrib[:attributes][:Province_State] || "").upcase == state.last else false end end def extract_attrib elem %i(Confirmed Deaths Recovered Active Last_Update).map do |k| elem[:attributes][k].to_i end end def get_data url = "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/" + "services/ncov_cases/FeatureServer/1/query?f=json&" + "where=Confirmed>0&outFields=*" c = HTTPClient.new r = c.get url msg = JSON.parse r.body, symbolize_names: true raise "HTTP Error #{r.code}: #{r.body}" unless r.code == 200 msg end end if __FILE__ == $0 require 'ostruct' class Plugin def initialize @bot = OpenStruct.new @bot.config = { } end def map *a end end end class Covid < Plugin attr_accessor :covid def initialize super self.covid = CovidAPI.new end def help(plugin, topic="") "COVID-19 stats plugin" end def message(m) end def command(m, params) begin argv = parse params.fetch(:command, []) data = get_data argv m.reply make_message data, argv rescue => e m.reply "Failed: #{e.message}" end end def make_message data, argv region = data[:region] || 'Global' d = data[:data] if argv[:color] out = [ "#{Bold}#{region}#{Bold}: ", "#{Bold}", "#{Irc.color(:olive)}", "#{d[0]}", "#{Irc.color}", " infected", "#{Bold}", " | ", "#{Bold}", "#{Irc.color(:red)}", "#{d[1]}", "#{Irc.color}", " dead (%.2f%%)" % (100.0 * d[1] / d[0]), "#{Bold}", " | ", "#{Bold}", "#{Irc.color(:limegreen)}", "#{d[2]}", "#{Irc.color}", " recovered", "#{Bold}", " | ", "#{Bold}", "Last update: #{format_time d[4]} ago", "#{Bold}", ].join else out = [ "#{region}: ", "#{d[0]}", " infected", " | ", "#{d[1]}", " dead (%.2f%%)" % (100.0 * d[1] / d[0]), " | ", "#{d[2]}", " recovered", " | ", "Last update: #{format_time d[4]} ago", ].join end end def format_time ts diff = Time.now - Time.at(ts/1000) if diff > 48 * 3600 "#{(diff.to_f / 86400).round 2} days" elsif diff > 5400 "#{(diff.to_f / 3600).round 2} hours" else "#{(diff.to_f / 60).round 1} minutes" end end def get_data argv if argv[:region] and argv[:region].size > 0 self.covid.get_from_region argv[:region] else self.covid.get_global end end def parse argv ret = { region: nil, color: true, } op = OptionParser.new do |o| o.on('--[no-]color'){ |v| ret[:color] = v } end rest = op.parse argv ret[:region] = rest.join(' ').upcase ret end def help_msg "Usage: REGION [--[no-]color]" end end plugin = Covid.new plugin.map 'covid *command', :action => :command plugin.map 'covid', :action => :command if __FILE__ == $0 begin c = CovidAPI.new c.get_data[:features].each do |x| p x end # r = plugin.parse "--no-color".split # p r # p plugin.get_data r # p plugin.convert r rescue => e puts e puts e.backtrace end end Fix last updated format for COVID. require 'httpclient' require 'json' require 'optparse' COUNTRIES = { "AF" => "AFGHANISTAN", "AX" => "ÅLAND ISLANDS", "AL" => "ALBANIA", "DZ" => "ALGERIA", "AS" => "AMERICAN SAMOA", "AD" => "ANDORRA", "AO" => "ANGOLA", "AI" => "ANGUILLA", "AQ" => "ANTARCTICA", "AG" => "ANTIGUA AND BARBUDA", "AR" => "ARGENTINA", "AM" => "ARMENIA", "AW" => "ARUBA", "AU" => "AUSTRALIA", "AT" => "AUSTRIA", "AZ" => "AZERBAIJAN", "BS" => "BAHAMAS, THE", "BH" => "BAHRAIN", "BD" => "BANGLADESH", "BB" => "BARBADOS", "BY" => "BELARUS", "BE" => "BELGIUM", "BZ" => "BELIZE", "BJ" => "BENIN", "BM" => "BERMUDA", "BT" => "BHUTAN", "BO" => "BOLIVIA", "BQ" => "BONAIRE", "BA" => "BOSNIA AND HERZEGOVINA", "BW" => "BOTSWANA", "BV" => "BOUVET ISLAND", "BR" => "BRAZIL", "IO" => "BRITISH INDIAN OCEAN TERRITORY", "BN" => "BRUNEI", "BG" => "BULGARIA", "BF" => "BURKINA FASO", "BI" => "BURUNDI", "KH" => "CAMBODIA", "CM" => "CAMEROON", "CA" => "CANADA", "CV" => "CAPE VERDE", "KY" => "CAYMAN ISLANDS", "CF" => "CENTRAL AFRICAN REPUBLIC", "TD" => "CHAD", "CL" => "CHILE", "CN" => "CHINA", "CX" => "CHRISTMAS ISLAND", "CC" => "COCOS ISLANDS", "CO" => "COLOMBIA", "KM" => "COMOROS", "CG" => "CONGO (BRAZZAVILLE)", "CD" => "CONGO (KINSHASA)", "CK" => "COOK ISLANDS", "CR" => "COSTA RICA", "CI" => "CÔTE D'IVOIRE", "HR" => "CROATIA", "CU" => "CUBA", "CW" => "CURAÇAO", "CY" => "CYPRUS", "CZ" => "CZECHIA", "DK" => "DENMARK", "DJ" => "DJIBOUTI", "DM" => "DOMINICA", "DO" => "DOMINICAN REPUBLIC", "EC" => "ECUADOR", "EG" => "EGYPT", "SV" => "EL SALVADOR", "GQ" => "EQUATORIAL GUINEA", "ER" => "ERITREA", "EE" => "ESTONIA", "ET" => "ETHIOPIA", "FK" => "FALKLAND ISLANDS", "FO" => "FAROE ISLANDS", "FJ" => "FIJI", "FI" => "FINLAND", "FR" => "FRANCE", "GF" => "GUIANA", "PF" => "POLYNESIA", "TF" => "FRENCH SOUTHERN TERRITORIES", "GA" => "GABON", "GM" => "GAMBIA, THE", "GE" => "GEORGIA", "DE" => "GERMANY", "GH" => "GHANA", "GI" => "GIBRALTAR", "GR" => "GREECE", "GL" => "GREENLAND", "GD" => "GRENADA", "GP" => "GUADELOUPE", "GU" => "GUAM", "GT" => "GUATEMALA", "GG" => "GUERNSEY", "GN" => "GUINEA", "GW" => "GUINEA-BISSAU", "GY" => "GUYANA", "HT" => "HAITI", "HM" => "HEARD ISLAND AND MCDONALD ISLANDS", "VA" => "HOLY SEE", "HN" => "HONDURAS", "HK" => "HONG KONG", "HU" => "HUNGARY", "IS" => "ICELAND", "IN" => "INDIA", "ID" => "INDONESIA", "IR" => "IRAN", "IQ" => "IRAQ", "IE" => "IRELAND", "IM" => "ISLE OF MAN", "IL" => "ISRAEL", "IT" => "ITALY", "JM" => "JAMAICA", "JP" => "JAPAN", "JE" => "JERSEY", "JO" => "JORDAN", "KZ" => "KAZAKHSTAN", "KE" => "KENYA", "KI" => "KIRIBATI", "KP" => "KOREA, NORTH", "KR" => "KOREA, SOUTH", "KW" => "KUWAIT", "KG" => "KYRGYZSTAN", "LA" => "LAOS", "LV" => "LATVIA", "LB" => "LEBANON", "LS" => "LESOTHO", "LR" => "LIBERIA", "LY" => "LIBYA", "LI" => "LIECHTENSTEIN", "LT" => "LITHUANIA", "LU" => "LUXEMBOURG", "MO" => "MACAO", "MK" => "NORTH MACEDONIA", "MG" => "MADAGASCAR", "MW" => "MALAWI", "MY" => "MALAYSIA", "MV" => "MALDIVES", "ML" => "MALI", "MT" => "MALTA", "MH" => "MARSHALL ISLANDS", "MQ" => "MARTINIQUE", "MR" => "MAURITANIA", "MU" => "MAURITIUS", "YT" => "MAYOTTE", "MX" => "MEXICO", "FM" => "MICRONESIA", "MD" => "MOLDOVA", "MC" => "MONACO", "MN" => "MONGOLIA", "ME" => "MONTENEGRO", "MS" => "MONTSERRAT", "MA" => "MOROCCO", "MZ" => "MOZAMBIQUE", "MM" => "MYANMAR", "NA" => "NAMIBIA", "NR" => "NAURU", "NP" => "NEPAL", "NL" => "NETHERLANDS", "NC" => "NEW CALEDONIA", "NZ" => "NEW ZEALAND", "NI" => "NICARAGUA", "NE" => "NIGER", "NG" => "NIGERIA", "NU" => "NIUE", "NF" => "NORFOLK ISLAND", "MP" => "NORTHERN MARIANA ISLANDS", "NO" => "NORWAY", "OM" => "OMAN", "PK" => "PAKISTAN", "PW" => "PALAU", "PS" => "PALESTINE, STATE OF", "PA" => "PANAMA", "PG" => "PAPUA NEW GUINEA", "PY" => "PARAGUAY", "PE" => "PERU", "PH" => "PHILIPPINES", "PN" => "PITCAIRN", "PL" => "POLAND", "PT" => "PORTUGAL", "PR" => "PUERTO RICO", "QA" => "QATAR", "RE" => "RÉUNION", "RO" => "ROMANIA", "RU" => "RUSSIA", "RW" => "RWANDA", "BL" => "SAINT BARTHÉLEMY", "SH" => "SAINT HELENA", "KN" => "SAINT KITTS AND NEVIS", "LC" => "SAINT LUCIA", "MF" => "SAINT MARTIN", "PM" => "SAINT PIERRE AND MIQUELON", "VC" => "SAINT VINCENT AND THE GRENADINES", "WS" => "SAMOA", "SM" => "SAN MARINO", "ST" => "SAO TOME AND PRINCIPE", "SA" => "SAUDI ARABIA", "SN" => "SENEGAL", "RS" => "SERBIA", "SC" => "SEYCHELLES", "SL" => "SIERRA LEONE", "SG" => "SINGAPORE", "SX" => "SINT MAARTEN", "SK" => "SLOVAKIA", "SI" => "SLOVENIA", "SB" => "SOLOMON ISLANDS", "SO" => "SOMALIA", "ZA" => "SOUTH AFRICA", "GS" => "GEORGIA", "SS" => "SOUTH SUDAN", "ES" => "SPAIN", "LK" => "SRI LANKA", "SD" => "SUDAN", "SR" => "SURINAME", "SJ" => "SVALBARD AND JAN MAYEN", "SZ" => "SWAZILAND", "SE" => "SWEDEN", "CH" => "SWITZERLAND", "SY" => "SYRIA", "TW" => "TAIWAN", "TJ" => "TAJIKISTAN", "TZ" => "TANZANIA", "TH" => "THAILAND", "TL" => "TIMOR-LESTE", "TG" => "TOGO", "TK" => "TOKELAU", "TO" => "TONGA", "TT" => "TRINIDAD AND TOBAGO", "TN" => "TUNISIA", "TR" => "TURKEY", "TM" => "TURKMENISTAN", "TC" => "TURKS AND CAICOS ISLANDS", "TV" => "TUVALU", "UG" => "UGANDA", "UA" => "UKRAINE", "AE" => "UNITED ARAB EMIRATES", "GB" => "UNITED KINGDOM", "UK" => "UNITED KINGDOM", "US" => "US", "UM" => "UNITED STATES MINOR OUTLYING ISLANDS", "UY" => "URUGUAY", "UZ" => "UZBEKISTAN", "VU" => "VANUATU", "VE" => "VENEZUELA", "VN" => "VIETNAM", "VG" => "VIRGIN ISLANDS", "VI" => "VIRGIN ISLANDS", "WF" => "WALLIS AND FUTUNA", "EH" => "WESTERN SAHARA", "YE" => "YEMEN", "ZM" => "ZAMBIA", "ZW" => "ZIMBABWE", } STATES = { 'AK' => 'ALASKA', 'AL' => 'ALABAMA', 'AR' => 'ARKANSAS', 'AS' => 'AMERICAN SAMOA', 'AZ' => 'ARIZONA', 'CA' => 'CALIFORNIA', 'CO' => 'COLORADO', 'CT' => 'CONNECTICUT', 'DC' => 'DISTRICT OF COLUMBIA', 'DE' => 'DELAWARE', 'FL' => 'FLORIDA', 'GA' => 'GEORGIA', 'GA-state' => 'GEORGIA', 'GU' => 'GUAM', 'HI' => 'HAWAII', 'IA' => 'IOWA', 'ID' => 'IDAHO', 'IL' => 'ILLINOIS', 'IN' => 'INDIANA', 'KS' => 'KANSAS', 'KY' => 'KENTUCKY', 'LA' => 'LOUISIANA', 'MA' => 'MASSACHUSETTS', 'MD' => 'MARYLAND', 'ME' => 'MAINE', 'MI' => 'MICHIGAN', 'MN' => 'MINNESOTA', 'MO' => 'MISSOURI', 'MP' => 'NORTHERN MARIANA ISLANDS', 'MS' => 'MISSISSIPPI', 'MT' => 'MONTANA', 'NA' => 'NATIONAL', 'NC' => 'NORTH CAROLINA', 'ND' => 'NORTH DAKOTA', 'NE' => 'NEBRASKA', 'NH' => 'NEW HAMPSHIRE', 'NJ' => 'NEW JERSEY', 'NM' => 'NEW MEXICO', 'NV' => 'NEVADA', 'NY' => 'NEW YORK', 'OH' => 'OHIO', 'OK' => 'OKLAHOMA', 'OR' => 'OREGON', 'PA' => 'PENNSYLVANIA', 'PR' => 'PUERTO RICO', 'RI' => 'RHODE ISLAND', 'SC' => 'SOUTH CAROLINA', 'SD' => 'SOUTH DAKOTA', 'TN' => 'TENNESSEE', 'TX' => 'TEXAS', 'UT' => 'UTAH', 'VA' => 'VIRGINIA', 'VI' => 'VIRGIN ISLANDS', 'VT' => 'VERMONT', 'WA' => 'WASHINGTON', 'WI' => 'WISCONSIN', 'WV' => 'WEST VIRGINIA', 'WY' => 'WYOMING', } class CovidAPI def initialize end def get_global { region: nil, data: format_data(get_data[:features]), } end def get_from_region region country = COUNTRIES.find{ |k, v| [k, v].include? region.upcase } state = STATES.find{ |k, v| [k, v].include? region.upcase } data = get_data[:features].select do |f| search_predicate f, region, country, state end raise "Region #{region} not found" unless data.size > 0 { region: COUNTRIES.fetch(region, STATES.fetch(region, region)), data: format_data(data), } end def format_data data funcs = [ :sum, :sum, :sum, :sum, :max ] data.map do |f| extract_attrib f end.transpose.zip(funcs).map do |zips| zips.first.reduce{ |t, n| [t, n].send zips.last } end end def search_predicate attrib, region, country, state if country (attrib[:attributes][:Country_Region] || "").upcase == country.last elsif state (attrib[:attributes][:Province_State] || "").upcase == state.last else false end end def extract_attrib elem %i(Confirmed Deaths Recovered Active Last_Update).map do |k| elem[:attributes][k].to_i end end def get_data url = "https://services1.arcgis.com/0MSEUqKaxRlEPj5g/arcgis/rest/" + "services/ncov_cases/FeatureServer/1/query?f=json&" + "where=Confirmed>0&outFields=*" c = HTTPClient.new r = c.get url msg = JSON.parse r.body, symbolize_names: true raise "HTTP Error #{r.code}: #{r.body}" unless r.code == 200 msg end end if __FILE__ == $0 require 'ostruct' class Plugin def initialize @bot = OpenStruct.new @bot.config = { } end def map *a end end end class Covid < Plugin attr_accessor :covid def initialize super self.covid = CovidAPI.new end def help(plugin, topic="") "COVID-19 stats plugin" end def message(m) end def command(m, params) begin argv = parse params.fetch(:command, []) data = get_data argv m.reply make_message data, argv rescue => e m.reply "Failed: #{e.message}" end end def make_message data, argv region = data[:region] || 'Global' d = data[:data] if argv[:color] out = [ "#{Bold}#{region}#{Bold}: ", "#{Bold}", "#{Irc.color(:olive)}", "#{d[0]}", "#{Irc.color}", " infected", "#{Bold}", " | ", "#{Bold}", "#{Irc.color(:red)}", "#{d[1]}", "#{Irc.color}", " dead (%.2f%%)" % (100.0 * d[1] / d[0]), "#{Bold}", " | ", "#{Bold}", "#{Irc.color(:limegreen)}", "#{d[2]}", "#{Irc.color}", " recovered", "#{Bold}", " | ", "#{Bold}", "Last update: #{format_time d[4]} ago", "#{Bold}", ].join else out = [ "#{region}: ", "#{d[0]}", " infected", " | ", "#{d[1]}", " dead (%.2f%%)" % (100.0 * d[1] / d[0]), " | ", "#{d[2]}", " recovered", " | ", "Last update: #{format_time d[4]} ago", ].join end end def format_time ts diff = Time.now - Time.at(ts/1000) diff = diff.to_i if diff > 24 * 3600 d = diff/86400 h = diff/3600%24 "#{d}d #{h}h" elsif diff > 3600 h = diff/3600 m = diff/60%60 "#{h}h #{m}m" else m = diff/60 s = diff%60 "#{m}m #{s}s" end end def get_data argv if argv[:region] and argv[:region].size > 0 self.covid.get_from_region argv[:region] else self.covid.get_global end end def parse argv ret = { region: nil, color: true, } op = OptionParser.new do |o| o.on('--[no-]color'){ |v| ret[:color] = v } end rest = op.parse argv ret[:region] = rest.join(' ').upcase ret end def help_msg "Usage: REGION [--[no-]color]" end end plugin = Covid.new plugin.map 'covid *command', :action => :command plugin.map 'covid', :action => :command if __FILE__ == $0 begin c = CovidAPI.new c.get_data[:features].each do |x| p x end # r = plugin.parse "--no-color".split # p r # p plugin.get_data r # p plugin.convert r rescue => e puts e puts e.backtrace end end
module ThorSCMVersion class MissingP4ConfigException < StandardError def initialize(config_option) @config_option = config_option end def message "#{@config_option} is not set in your environment." end end module Perforce class << self def check_environment ["P4PORT","P4USER", "P4PASSWD", "P4CLIENT"].each {|config| raise MissingP4ConfigException.new(config) if ENV[config].nil? or ENV[config].empty? } end def set ShellUtils.sh "p4 set" end def parse_and_set_p4_set p4_set = set parsed_p4_config = p4_set.split("\n").inject({}) do |p4_config, line| key, value = line.split('=') value = value.gsub(/\(.*/, '').strip unless value.nil? p4_config[key] = value p4_config end parsed_p4_config.each {|key,value| ENV[key] = value} end def connection parse_and_set_p4_set check_environment ShellUtils.sh "echo #{ENV["P4PASSWD"]} | p4 login" yield ensure ShellUtils.sh "p4 logout" end end end class P4Version < ScmVersion class << self def all_from_path(path) Dir.chdir(path) do p4_depot_files = ShellUtils.sh("p4 dirs #{File.expand_path(path)}").chomp p4_module_name = File.expand_path(path).split("/").last all_labels_array = ShellUtils.sh("p4 labels -e \"#{p4_module_name}*\" #{p4_depot_files}/...").split("\n") thor_scmversion_labels = all_labels_array.select{|label| label.split(" ")[1].gsub("#{p4_module_name}-", "").match(ScmVersion::VERSION_FORMAT)} current_versions = thor_scmversion_labels.collect do |label| new_instance = new(*parse_label(label, p4_module_name), p4_module_name, path) new_instance end.sort.reverse current_versions << new(0, 0, 0, p4_module_name, path) if current_versions.empty? current_versions end end def parse_label(label, p4_module_name) label.split(" ")[1].gsub("#{p4_module_name}-", "").split('.') end end attr_accessor :version_file_path attr_accessor :p4_module_name attr_accessor :path def initialize(major, minor, patch, p4_module_name, path) @major = major.to_i @minor = minor.to_i @patch = patch.to_i @p4_module_name = p4_module_name @path = path end def retrieve_tags # noop # p4 always has labels available, you just have to ask the server for them. end def tag `p4 label -o #{get_label_name}` `p4 tag -l #{get_label_name} #{File.join(File.expand_path(path), "")}...#head` end def auto_bump # TODO: actually implement this bump!(:patch) end private def get_label_name "#{p4_module_name}-#{self}" end end end renaming variable module ThorSCMVersion class MissingP4ConfigException < StandardError def initialize(config_option) @config_option = config_option end def message "#{@config_option} is not set in your environment." end end module Perforce class << self def check_environment ["P4PORT","P4USER", "P4PASSWD", "P4CLIENT"].each {|config| raise MissingP4ConfigException.new(config) if ENV[config].nil? or ENV[config].empty? } end def set ShellUtils.sh "p4 set" end def parse_and_set_p4_set p4_set = set parsed_p4_config = p4_set.split("\n").inject({}) do |p4_config, line| key, value = line.split('=') value = value.gsub(/\(.*/, '').strip unless value.nil? p4_config[key] = value p4_config end parsed_p4_config.each {|key,value| ENV[key] = value} end def connection parse_and_set_p4_set check_environment ShellUtils.sh "echo #{ENV["P4PASSWD"]} | p4 login" yield ensure ShellUtils.sh "p4 logout" end end end class P4Version < ScmVersion class << self def all_from_path(path) Dir.chdir(path) do p4_depot_path = ShellUtils.sh("p4 dirs #{File.expand_path(path)}").chomp p4_module_name = File.expand_path(path).split("/").last all_labels_array = ShellUtils.sh("p4 labels -e \"#{p4_module_name}*\" #{p4_depot_path}/...").split("\n") thor_scmversion_labels = all_labels_array.select{|label| label.split(" ")[1].gsub("#{p4_module_name}-", "").match(ScmVersion::VERSION_FORMAT)} current_versions = thor_scmversion_labels.collect do |label| new_instance = new(*parse_label(label, p4_module_name), p4_module_name, path) new_instance end.sort.reverse current_versions << new(0, 0, 0, p4_module_name, path) if current_versions.empty? current_versions end end def parse_label(label, p4_module_name) label.split(" ")[1].gsub("#{p4_module_name}-", "").split('.') end end attr_accessor :version_file_path attr_accessor :p4_module_name attr_accessor :path def initialize(major, minor, patch, p4_module_name, path) @major = major.to_i @minor = minor.to_i @patch = patch.to_i @p4_module_name = p4_module_name @path = path end def retrieve_tags # noop # p4 always has labels available, you just have to ask the server for them. end def tag `p4 label -o #{get_label_name}` `p4 tag -l #{get_label_name} #{File.join(File.expand_path(path), "")}...#head` end def auto_bump # TODO: actually implement this bump!(:patch) end private def get_label_name "#{p4_module_name}-#{self}" end end end
module Tirade module FormBuilderHelper def text_field(field, options = {}) wrap(field, options, super(field,options)) end def text_area(field, options = {}) wrap(field, options, super(field,options.reverse_merge(:rows => 2))) end def collection_select(field, collection, value_method, text_method, options = {}, html_options = {}) wrap(field, options, super(field, collection, value_method, text_method, options, html_options)) end def select(field, choices, options = {}, html_options = {}) wrap(field,options, super(field, choices, options, html_options)) end def check_box(field, options = {}, checked_value = "1", unchecked_value = "0") options[:class] ||= '' options[:class] += ' checkbox' wrap(field, options,super(field, options, checked_value, unchecked_value)) end def select_picture has_many :images, :foreign_key => 'image_ids' end def has_many(assoc, opts={}) unless @object.class.reflections.has_key?(assoc) return "does not know about #{assoc.to_s.humanize}" end reflection = @object.class.reflections[assoc] return "Wrong association type (#{reflection.macro}), needed has_many" unless reflection.macro == :has_many things = @object.send(assoc) fkey = opts.delete(:foreign_key) || "#{assoc.to_s.singularize}_ids" inner = '' inner << @template.list_of(things, :force_list => true) inner << @template.text_field_tag("#{assoc}_search_term", nil, :href => @template.url_for(:controller => assoc), :class => 'search_term') inner << @template.content_tag(:div, "Search for #{assoc.to_s.humanize}", :class => "search_results many #{assoc}") inner << @template.hidden_field_tag("#{@object_name}[#{fkey}][]","empty") wrap(assoc, {}, inner) end def has_one(assoc, opts={}) unless @object.class.reflections.has_key?(assoc) return "does not know about #{assoc.to_s.humanize}" end reflection = @object.class.reflections[assoc] return "Wrong association type (#{reflection.macro}), needed belongs_to/has_one" unless [:has_one, :belongs_to].include?(reflection.macro) assocs = assoc.to_s.pluralize thing = @object.send(assoc) inner = '' inner << @template.content_tag( :ul, @template.list_item(thing), :class => 'association one list' ) inner << @template.text_field_tag("#{assoc}_search_term", nil, :href => @template.url_for(:controller => assocs), :class => 'search_term') inner << @template.content_tag(:div, "Search for #{assocs.humanize}", :class => "search_results one #{assocs}") inner << @template.hidden_field_tag("#{@object_name}[#{assoc}_id]", thing.id, :class => 'association_id') if reflection.options[:polymorphic] inner << @template.hidden_field_tag("#{@object_name}[#{reflection.options[:foreign_type]}]", thing.class_name, :class => 'association_type') end wrap(assoc, {}, inner) end private def wrap(field, options, tag_output) label = @template.content_tag( :label, (options.delete(:label) || field.to_s.humanize), {:for => "#{@object_name.to_s}_#{field}"} ) @template.content_tag( :div, label + ' ' + tag_output, {:class => field.to_s} ) end end end (m) nicer code git-svn-id: d95c7f39bc46a13f717da3baac7edcc188a27d76@1575 9df96bbd-a318-0410-8f51-977bef1cc4bb module Tirade module FormBuilderHelper def text_field(field, options = {}) wrap(field, options, super(field,options)) end def text_area(field, options = {}) wrap(field, options, super(field,options.reverse_merge(:rows => 2))) end def collection_select(field, collection, value_method, text_method, options = {}, html_options = {}) wrap(field, options, super(field, collection, value_method, text_method, options, html_options)) end def select(field, choices, options = {}, html_options = {}) wrap(field,options, super(field, choices, options, html_options)) end def check_box(field, options = {}, checked_value = "1", unchecked_value = "0") options[:class] ||= '' options[:class] += ' checkbox' wrap(field, options,super(field, options, checked_value, unchecked_value)) end def select_picture has_many :images, :foreign_key => 'image_ids' end def has_many(assoc, opts={}) unless @object.class.reflections.has_key?(assoc) return "does not know about #{assoc.to_s.humanize}" end reflection = @object.class.reflections[assoc] return "Wrong association type (#{reflection.macro}), needed has_many" unless reflection.macro == :has_many things = @object.send(assoc) fkey = opts.delete(:foreign_key) || "#{assoc.to_s.singularize}_ids" inner = '' inner << @template.list_of(things, :force_list => true) href = @template.url_for(:controller => assoc) inner << @template.text_field_tag("#{assoc}_search_term", nil, :href => href, :class => 'search_term') inner << @template.content_tag(:div, "Search for #{assoc.to_s.humanize}", :class => "search_results many #{assoc}") inner << @template.hidden_field_tag("#{@object_name}[#{fkey}][]","empty") wrap(assoc, {}, inner) end def has_one(assoc, opts={}) unless @object.class.reflections.has_key?(assoc) return "does not know about #{assoc.to_s.humanize}" end reflection = @object.class.reflections[assoc] return "Wrong association type (#{reflection.macro}), needed belongs_to/has_one" unless [:has_one, :belongs_to].include?(reflection.macro) assocs = assoc.to_s.pluralize thing = @object.send(assoc) inner = '' inner << @template.content_tag( :ul, @template.list_item(thing), :class => 'association one list' ) inner << @template.text_field_tag("#{assoc}_search_term", nil, :href => @template.url_for(:controller => assocs), :class => 'search_term') inner << @template.content_tag(:div, "Search for #{assocs.humanize}", :class => "search_results one #{assocs}") inner << @template.hidden_field_tag("#{@object_name}[#{assoc}_id]", thing.id, :class => 'association_id') if reflection.options[:polymorphic] inner << @template.hidden_field_tag("#{@object_name}[#{reflection.options[:foreign_type]}]", thing.class_name, :class => 'association_type') end wrap(assoc, {}, inner) end private def wrap(field, options, tag_output) label = @template.content_tag( :label, (options.delete(:label) || field.to_s.humanize), {:for => "#{@object_name.to_s}_#{field}"} ) @template.content_tag( :div, label + ' ' + tag_output, {:class => field.to_s} ) end end end
require 'sparql/client' module TogoStanza::Stanza module Querying MAPPINGS = { togogenome: 'http://togogenome.org/sparql' } def query(endpoint, sparql) client = SPARQL::Client.new(MAPPINGS[endpoint] || endpoint) #Rails.logger.debug "SPARQL QUERY: \n#{sparql}" client.query(sparql).map {|binding| binding.each_with_object({}) {|(name, term), hash| hash[name] = term.to_s } } end end end Be able to use the sparql path in the second argument require 'sparql/client' require 'flavour_saver' module TogoStanza::Stanza module Querying MAPPINGS = { togogenome: 'http://togogenome.org/sparql' } def query(endpoint, text_or_filename) path = File.join(root, 'sparql', text_or_filename) if File.exist?(path) data = OpenStruct.new params text_or_filename = Tilt.new(path).render(data) end client = SPARQL::Client.new(MAPPINGS[endpoint] || endpoint) #Rails.logger.debug "SPARQL QUERY: \n#{sparql}" client.query(text_or_filename).map {|binding| binding.each_with_object({}) {|(name, term), hash| hash[name] = term.to_s } } end end end
module TransamAccounting VERSION = "0.1.34" end Bump version module TransamAccounting VERSION = "0.1.35" end
class Transilien::VehicleJourney < Transilien::MicroService end WIP VehicleJourney, need to define helper objet Stop to handle the StopPoint StopArea and other datas class Transilien::VehicleJourney < Transilien::MicroService def route @route ||= Transilien::Route.from_node(payload.at('Route'), access_time) end def mode @mode ||= Transilien::Mode.from_node(payload.at('Mode'), access_time) end def company @company ||= Transilien::Company.from_node(payload.at('Company'), access_time) end def vehicle @vehicle ||= payload.at('Vehicle') end def validity_pattern @validity_pattern ||= payload.at('ValidityPattern') end def stops @stops ||= begin stops_node = payload.at('StopList') new_stops = [] end end end
module Transmission module Model class Torrent class TorrentError < StandardError; end class TorrentNotFoundError < StandardError; end class MissingAttributesError < StandardError; end class DuplicateTorrentError < StandardError; end attr_accessor :attributes, :deleted, :connector, :torrents, :ids def initialize(torrent_object, connector) if torrent_object.is_a? Array is_single = torrent_object.size == 1 @attributes = is_single ? torrent_object.first : {} @ids = is_single ? [@attributes['id'].to_i] : [] @torrents = torrent_object.inject([]) do |torrents, torrent| @ids << torrent['id'].to_i torrents << Torrent.new([torrent], connector) end unless is_single end @connector = connector end def delete!(remove_local_data = false) connector.remove_torrent @ids, remove_local_data @deleted = true end def save! filtered = Transmission::Arguments::TorrentSet.filter @attributes connector.set_torrent @ids, filtered end def move_up! connector.move_up_torrent @ids end def move_down! connector.move_down_torrent @ids end def move_top! connector.move_top_torrent @ids end def move_bottom! connector.move_bottom_torrent @ids end def start! connector.start_torrent @ids end def start_now! connector.start_torrent_now @ids end def stop! connector.stop_torrent @ids end def verify! connector.verify_torrent @ids end def re_announce! connector.re_announce_torrent @ids end def torrent_set_location(options = {}) connector.torrent_set_location options end def is_multi? @ids.size > 1 end def finished? self.percent_done == 1 end def reload! torrents = Torrent.find @ids, connector: @connector @ids = torrents.ids @attributes = torrents.attributes @torrents = torrents.torrents end def to_json if is_multi? @torrents.inject([]) do |torrents, torrent| torrents << torrent.to_json end else @attributes end end def method_missing(symbol, *args) string = symbol.to_s if string[-1] == '=' string = string[0..-2] key = Transmission::Arguments::TorrentSet.real_key string return @attributes[key] = args.first if !!key else key = Transmission::Fields::TorrentGet.real_key string return @attributes[key] if !!key end super end class << self def all(options = {}) rpc = options[:connector] || connector body = rpc.get_torrent nil, options[:fields] Torrent.new body['torrents'], rpc end def find(id, options = {}) rpc = options[:connector] || connector ids = id.is_a?(Array) ? id : [id] raise TorrentNotFoundError if body['torrents'].size == 0 Torrent.new body['torrents'], rpc end def add(options = {}) rpc = options[:connector] || connector body = rpc.add_torrent options[:arguments] raise DuplicateTorrentError if body['torrent-duplicate'] find body['torrent-added']['id'], options end def start_all!(options = {}) rpc = options[:connector] || connector rpc.start_torrent nil end def stop_all!(options = {}) rpc = options[:connector] || connector rpc.stop_torrent nil end def connector Transmission::Config.get_connector end end end end end return standard errors module Transmission module Model class Torrent class TorrentError < StandardError; end class TorrentNotFoundError < StandardError; end class MissingAttributesError < StandardError; end class DuplicateTorrentError < StandardError; end attr_accessor :attributes, :deleted, :connector, :torrents, :ids def initialize(torrent_object, connector) if torrent_object.is_a? Array is_single = torrent_object.size == 1 @attributes = is_single ? torrent_object.first : {} @ids = is_single ? [@attributes['id'].to_i] : [] @torrents = torrent_object.inject([]) do |torrents, torrent| @ids << torrent['id'].to_i torrents << Torrent.new([torrent], connector) end unless is_single end @connector = connector end def delete!(remove_local_data = false) connector.remove_torrent @ids, remove_local_data @deleted = true end def save! filtered = Transmission::Arguments::TorrentSet.filter @attributes connector.set_torrent @ids, filtered end def move_up! connector.move_up_torrent @ids end def move_down! connector.move_down_torrent @ids end def move_top! connector.move_top_torrent @ids end def move_bottom! connector.move_bottom_torrent @ids end def start! connector.start_torrent @ids end def start_now! connector.start_torrent_now @ids end def stop! connector.stop_torrent @ids end def verify! connector.verify_torrent @ids end def re_announce! connector.re_announce_torrent @ids end def torrent_set_location(options = {}) connector.torrent_set_location options end def is_multi? @ids.size > 1 end def finished? self.percent_done == 1 end def reload! torrents = Torrent.find @ids, connector: @connector @ids = torrents.ids @attributes = torrents.attributes @torrents = torrents.torrents end def to_json if is_multi? @torrents.inject([]) do |torrents, torrent| torrents << torrent.to_json end else @attributes end end def method_missing(symbol, *args) string = symbol.to_s if string[-1] == '=' string = string[0..-2] key = Transmission::Arguments::TorrentSet.real_key string return @attributes[key] = args.first if !!key else key = Transmission::Fields::TorrentGet.real_key string return @attributes[key] if !!key end super end class << self def all(options = {}) rpc = options[:connector] || connector body = rpc.get_torrent nil, options[:fields] Torrent.new body['torrents'], rpc end def find(id, options = {}) rpc = options[:connector] || connector ids = id.is_a?(Array) ? id : [id] body = rpc.get_torrent ids, options[:fields] raise TorrentNotFoundError if body['torrents'].size == 0 Torrent.new body['torrents'], rpc end def add(options = {}) rpc = options[:connector] || connector body = rpc.add_torrent options[:arguments] raise DuplicateTorrentError if body['torrent-duplicate'] find body['torrent-added']['id'], options end def start_all!(options = {}) rpc = options[:connector] || connector rpc.start_torrent nil end def stop_all!(options = {}) rpc = options[:connector] || connector rpc.stop_torrent nil end def connector Transmission::Config.get_connector end end end end end
require 'metriks' module Travis class Hub class Handler class Request < Handler # Handles request messages which are created by the listener # when a github event comes in. class ProcessingError < StandardError; end attr_reader :user def type payload['type'] end def credentials payload['credentials'] end def data @data ||= payload['payload'] ? MultiJson.decode(payload['payload']) : nil end def handle raise(ProcessingError, "the #{type} payload was empty and could not be processed") unless data receive if authenticated? end instrument :handle, :scope => :type new_relic :handle private def receive Travis.run_service(:receive_request, user, :event_type => type, :payload => data, :token => credentials['token']) end def requeue Travis.run_service(:requeue_request, user, :build_id => payload['build_id'], :token => credentials['token']) .run end # TODO move authentication to the service def authenticated? !!authenticate end def authenticate p credentials @user = User.authenticate_by(credentials) end instrument :authenticate, :scope => :type Travis::Hub::Instrument::Handler::Request.attach_to(self) end end end end remove debug output require 'metriks' module Travis class Hub class Handler class Request < Handler # Handles request messages which are created by the listener # when a github event comes in. class ProcessingError < StandardError; end attr_reader :user def type payload['type'] end def credentials payload['credentials'] end def data @data ||= payload['payload'] ? MultiJson.decode(payload['payload']) : nil end def handle raise(ProcessingError, "the #{type} payload was empty and could not be processed") unless data receive if authenticated? end instrument :handle, :scope => :type new_relic :handle private def receive Travis.run_service(:receive_request, user, :event_type => type, :payload => data, :token => credentials['token']) end def requeue Travis.run_service(:requeue_request, user, :build_id => payload['build_id'], :token => credentials['token']) .run end # TODO move authentication to the service def authenticated? !!authenticate end def authenticate @user = User.authenticate_by(credentials) end instrument :authenticate, :scope => :type Travis::Hub::Instrument::Handler::Request.attach_to(self) end end end end
require 'bio' require 'bettersam' require 'csv' require 'forwardable' require 'inline' module Transrate class Assembly include Enumerable extend Forwardable def_delegators :@assembly, :each, :<<, :size, :length attr_accessor :ublast_db attr_accessor :orfs_ublast_db attr_accessor :protein attr_reader :assembly attr_reader :has_run # number of bases in the assembly attr_writer :n_bases # assembly filename attr_accessor :file # assembly n50 attr_reader :n50 # Return a new Assembly. # # - +:file+ - path to the assembly FASTA file def initialize file @file = file @assembly = [] @n_bases = 0 Bio::FastaFormat.open(file).each do |entry| @n_bases += entry.length @assembly << entry end end # Return a new Assembly object by loading sequences # from the FASTA-format +:file+ def self.stats_from20_fasta file a = Assembly.new file a.basic_stats end def run threads=8 stats = self.basic_stats threads stats.each_pair do |key, value| ivar = "@#{key.gsub(/\ /, '_')}".to_sym attr_ivar = "#{key.gsub(/\ /, '_')}".to_sym # creates accessors for the variables in stats singleton_class.class_eval { attr_accessor attr_ivar } self.instance_variable_set(ivar, value) end @has_run = true end # Return a hash of statistics about this assembly. Stats are # calculated in parallel by splitting the assembly into # equal-sized bins and calling Assembly#basic_bin_stat on each # bin in a separate thread. def basic_stats threads=8 # create a work queue to process contigs in parallel queue = Queue.new # split the contigs into equal sized bins, one bin per thread binsize = (@assembly.size / threads.to_f).ceil # Transrate.log.info("Processing #{@assembly.size} contigs in #{threads} bins") @assembly.each_slice(binsize) do |bin| queue << bin end # a classic threadpool - an Array of threads that allows # us to assign work to each thread and then aggregate their # results when they are all finished threadpool = [] # assign one bin of contigs to each thread from the queue. # each thread will process its bin of contigs and then wait # for the others to finish. semaphore = Mutex.new stats = [] threads.times do threadpool << Thread.new do |thread| # keep looping until we run out of bins until queue.empty? # use non-blocking pop, so an exception is raised # when the queue runs dry bin = queue.pop(true) rescue nil if bin # calculate basic stats for the bin, storing them # in the current thread so they can be collected # in the main thread. bin_stats = basic_bin_stats bin semaphore.synchronize { stats << bin_stats } end end end end # collect the stats calculated in each thread and join # the threads to terminate them threadpool.each(&:join) # merge the collected stats and return then merge_basic_stats stats end # basic_stats # Calculate basic statistics in an single thread for a bin # of contigs. # # Basic statistics are: # # - N10, N30, N50, N70, N90 # - number of contigs >= 1,000 base pairs long # - number of contigs >= 10,000 base pairs long # - length of the shortest contig # - length of the longest contig # - number of contigs in the bin # - mean contig length # - total number of nucleotides in the bin # - mean % of contig length covered by the longest ORF # # @param [Array] bin An array of Bio::Sequence objects # representing contigs in the assembly def basic_bin_stats bin # cumulative length is a float so we can divide it # accurately later to get the mean length cumulative_length = 0.0 # we'll calculate Nx for x in [10, 30, 50, 70, 90] # to do this we create a stack of the x values and # pop the first one to set the first cutoff. when # the cutoff is reached we store the nucleotide length and pop # the next value to set the next cutoff. we take a copy # of the Array so we can use the intact original to collect # the results later # x = [90, 70, 50, 30, 10] # x2 = x.clone # cutoff = x2.pop / 100.0 # res = [] n1k = 0 n10k = 0 orf_length_sum = 0 # sort the contigs in ascending length order # and iterate over them bin.sort_by! { |c| c.seq.size } bin.each do |contig| # increment our long contig counters if this # contig is above the thresholds n1k += 1 if contig.length > 1_000 n10k += 1 if contig.length > 10_000 # add the length of the longest orf to the # running total orf_length_sum += orf_length(contig.seq) # increment the cumulative length and check whether the Nx # cutoff has been reached. if it has, store the Nx value and # get the next cutoff cumulative_length += contig.length # if cumulative_length >= @n_bases * cutoff # res << contig.length # if x2.empty? # cutoff=1 # else # cutoff = x2.pop / 100.0 # end # end end # calculate and return the statistics as a hash mean = cumulative_length / @assembly.size # ns = Hash[x.map { |n| "N#{n}" }.zip(res)] { "n_seqs" => bin.size, "smallest" => bin.first.length, "largest" => bin.last.length, "n_bases" => n_bases, "mean_len" => mean, "n_1k" => n1k, "n_10k" => n10k, "orf_percent" => 300 * orf_length_sum / (@assembly.size * mean) } # }.merge ns end # basic_bin_stats def merge_basic_stats stats # convert the array of hashes into a hash of arrays collect = Hash.new{|h,k| h[k]=[]} stats.each_with_object(collect) do |collect, result| collect.each{ |k, v| result[k] << v } end merged = {} collect.each_pair do |stat, values| if stat == 'orf_percent' || /N[0-9]{2}/ =~ stat # store the mean merged[stat] = values.inject(:+) / values.size elsif stat == 'smallest' merged[stat] = values.min elsif stat == 'largest' merged[stat] = values.max else # store the sum merged[stat] = values.inject(:+) end end merged end # merge_basic_stats inline do |builder| builder.c " static void load_array(VALUE _s) { int sl = RARRAY_LEN(_s); int s[sl]; int i,f; int len = 0; int longest = 0; VALUE *sv = RARRAY_PTR(_s); for (i=0; i < sl; i++) { s[i] = NUM2INT(sv[i]); } for (f=0; f<3; f++) { len=0; for (i=f; i < sl-2; i+=3) { if (s[i]==84 && ((s[i+1]==65 && s[i+2]==71) || (s[i+1]==65 && s[i+2]==65) || (s[i+1]==71 && s[i+2]==65))) { if (len > longest) { longest = len; } len=0; } else { len++; } } if (len > longest) { longest = len; } } for (f=0; f<3; f++) { len=0; for (i=sl-1-f;i>=0;i-=3) { if ((s[i]==65 && s[i-1]==84 && s[i-2]==67) || (s[i]==65 && s[i-1]==84 && s[i-2]==84) || (s[i]==65 && s[i-1]==67 && s[i-2]==84)) { if (len > longest) { longest = len; } len = 0; } else { len++; } } } if (len > longest) { longest = len; } return INT2NUM(longest); } " end # finds longest orf in a sequence def orf_length sequence longest = load_array(sequence.unpack("U*")) return longest end # return the number of bases in the assembly, calculating # from the assembly if it hasn't already been done. def n_bases unless @n_bases @n_bases = 0 @assembly.each { |s| @n_bases += s.length } end @n_bases end def print_stats self.basic_stats.map do |k, v| "#{k}#{" " * (20 - (k.length + v.to_i.to_s.length))}#{v.to_i}" end.join("\n") end end # Assembly end # Transrate Incline C version of orf_length, uncomment logger Former-commit-id: 184c5e490f8b5c5224f51a690b5750f483ef6b2e require 'bio' require 'bettersam' require 'csv' require 'forwardable' require 'inline' module Transrate class Assembly include Enumerable extend Forwardable def_delegators :@assembly, :each, :<<, :size, :length attr_accessor :ublast_db attr_accessor :orfs_ublast_db attr_accessor :protein attr_reader :assembly attr_reader :has_run # number of bases in the assembly attr_writer :n_bases # assembly filename attr_accessor :file # assembly n50 attr_reader :n50 # Return a new Assembly. # # - +:file+ - path to the assembly FASTA file def initialize file @file = file @assembly = [] @n_bases = 0 Bio::FastaFormat.open(file).each do |entry| @n_bases += entry.length @assembly << entry end end # Return a new Assembly object by loading sequences # from the FASTA-format +:file+ def self.stats_from20_fasta file a = Assembly.new file a.basic_stats end def run threads=8 stats = self.basic_stats threads stats.each_pair do |key, value| ivar = "@#{key.gsub(/\ /, '_')}".to_sym attr_ivar = "#{key.gsub(/\ /, '_')}".to_sym # creates accessors for the variables in stats singleton_class.class_eval { attr_accessor attr_ivar } self.instance_variable_set(ivar, value) end @has_run = true end # Return a hash of statistics about this assembly. Stats are # calculated in parallel by splitting the assembly into # equal-sized bins and calling Assembly#basic_bin_stat on each # bin in a separate thread. def basic_stats threads=8 # create a work queue to process contigs in parallel queue = Queue.new # split the contigs into equal sized bins, one bin per thread binsize = (@assembly.size / threads.to_f).ceil Transrate.log.info("Processing #{@assembly.size} contigs in #{threads} bins") @assembly.each_slice(binsize) do |bin| queue << bin end # a classic threadpool - an Array of threads that allows # us to assign work to each thread and then aggregate their # results when they are all finished threadpool = [] # assign one bin of contigs to each thread from the queue. # each thread will process its bin of contigs and then wait # for the others to finish. semaphore = Mutex.new stats = [] threads.times do threadpool << Thread.new do |thread| # keep looping until we run out of bins until queue.empty? # use non-blocking pop, so an exception is raised # when the queue runs dry bin = queue.pop(true) rescue nil if bin # calculate basic stats for the bin, storing them # in the current thread so they can be collected # in the main thread. bin_stats = basic_bin_stats bin semaphore.synchronize { stats << bin_stats } end end end end # collect the stats calculated in each thread and join # the threads to terminate them threadpool.each(&:join) # merge the collected stats and return then merge_basic_stats stats end # basic_stats # Calculate basic statistics in an single thread for a bin # of contigs. # # Basic statistics are: # # - N10, N30, N50, N70, N90 # - number of contigs >= 1,000 base pairs long # - number of contigs >= 10,000 base pairs long # - length of the shortest contig # - length of the longest contig # - number of contigs in the bin # - mean contig length # - total number of nucleotides in the bin # - mean % of contig length covered by the longest ORF # # @param [Array] bin An array of Bio::Sequence objects # representing contigs in the assembly def basic_bin_stats bin # cumulative length is a float so we can divide it # accurately later to get the mean length cumulative_length = 0.0 # we'll calculate Nx for x in [10, 30, 50, 70, 90] # to do this we create a stack of the x values and # pop the first one to set the first cutoff. when # the cutoff is reached we store the nucleotide length and pop # the next value to set the next cutoff. we take a copy # of the Array so we can use the intact original to collect # the results later # x = [90, 70, 50, 30, 10] # x2 = x.clone # cutoff = x2.pop / 100.0 # res = [] n1k = 0 n10k = 0 orf_length_sum = 0 # sort the contigs in ascending length order # and iterate over them bin.sort_by! { |c| c.seq.size } bin.each do |contig| # increment our long contig counters if this # contig is above the thresholds n1k += 1 if contig.length > 1_000 n10k += 1 if contig.length > 10_000 # add the length of the longest orf to the # running total orf_length_sum += orf_length(contig.seq) # increment the cumulative length and check whether the Nx # cutoff has been reached. if it has, store the Nx value and # get the next cutoff cumulative_length += contig.length # if cumulative_length >= @n_bases * cutoff # res << contig.length # if x2.empty? # cutoff=1 # else # cutoff = x2.pop / 100.0 # end # end end # calculate and return the statistics as a hash mean = cumulative_length / @assembly.size # ns = Hash[x.map { |n| "N#{n}" }.zip(res)] { "n_seqs" => bin.size, "smallest" => bin.first.length, "largest" => bin.last.length, "n_bases" => n_bases, "mean_len" => mean, "n_1k" => n1k, "n_10k" => n10k, "orf_percent" => 300 * orf_length_sum / (@assembly.size * mean) } # }.merge ns end # basic_bin_stats def merge_basic_stats stats # convert the array of hashes into a hash of arrays collect = Hash.new{|h,k| h[k]=[]} stats.each_with_object(collect) do |collect, result| collect.each{ |k, v| result[k] << v } end merged = {} collect.each_pair do |stat, values| if stat == 'orf_percent' || /N[0-9]{2}/ =~ stat # store the mean merged[stat] = values.inject(:+) / values.size elsif stat == 'smallest' merged[stat] = values.min elsif stat == 'largest' merged[stat] = values.max else # store the sum merged[stat] = values.inject(:+) end end merged end # merge_basic_stats inline do |builder| builder.c " static void load_array(VALUE _s) { int sl = RARRAY_LEN(_s); int s[sl]; int i,f; int len = 0; int longest = 0; VALUE *sv = RARRAY_PTR(_s); for (i=0; i < sl; i++) { s[i] = NUM2INT(sv[i]); } for (f=0; f<3; f++) { len=0; for (i=f; i < sl-2; i+=3) { if (s[i]==84 && ((s[i+1]==65 && s[i+2]==71) || (s[i+1]==65 && s[i+2]==65) || (s[i+1]==71 && s[i+2]==65))) { if (len > longest) { longest = len; } len=0; } else { len++; } } if (len > longest) { longest = len; } } for (f=0; f<3; f++) { len=0; for (i=sl-1-f;i>=0;i-=3) { if ((s[i]==65 && s[i-1]==84 && s[i-2]==67) || (s[i]==65 && s[i-1]==84 && s[i-2]==84) || (s[i]==65 && s[i-1]==67 && s[i-2]==84)) { if (len > longest) { longest = len; } len = 0; } else { len++; } } } if (len > longest) { longest = len; } return INT2NUM(longest); } " end # finds longest orf in a sequence def orf_length sequence longest = load_array(sequence.unpack("U*")) return longest end # return the number of bases in the assembly, calculating # from the assembly if it hasn't already been done. def n_bases unless @n_bases @n_bases = 0 @assembly.each { |s| @n_bases += s.length } end @n_bases end def print_stats self.basic_stats.map do |k, v| "#{k}#{" " * (20 - (k.length + v.to_i.to_s.length))}#{v.to_i}" end.join("\n") end end # Assembly end # Transrate
require 'active_record' require 'core_ext/active_record/base' require 'core_ext/hash/deep_symbolize_keys' require 'simple_states' # Build currently models a central but rather abstract domain entity: the thing # that is triggered by a Github request (service hook ping). # # Build groups a matrix of Job::Test instances, and belongs to a Request (and # thus Commit as well as a Repository). # # A Build is created when its Request was configured (by fetching .travis.yml) # and approved (e.g. not excluded by the configuration). Once a Build is # created it will expand its matrix according to the given configuration and # create the according Job::Test instances. Each Job::Test instance will # trigger a test run remotely (on the worker). Once all Job::Test instances # have finished the Build will be finished as well. # # Each of these state changes (build:created, job:started, job:finished, ...) # will issue events that are listened for by the event handlers contained in # travis/notification. These event handlers then send out various notifications # of various types through email, pusher and irc, archive builds and queue # jobs for the workers. # # Build is split up to several modules: # # * Build - ActiveRecord structure, validations and scopes # * States - state definitions and events # * Denormalize - some state changes denormalize attributes to the build's # repository (e.g. Build#started_at gets propagated to # Repository#last_started_at) # * Matrix - logic related to expanding the build matrix, normalizing # configuration for Job::Test instances, evaluating the # final build result etc. # * Messages - helpers for evaluating human readable result messages # (e.g. "Still Failing") # * Events - helpers that are used by notification handlers (and that # TODO probably should be cleaned up and moved to # travis/notification) class Build < ActiveRecord::Base autoload :Denormalize, 'travis/model/build/denormalize' autoload :Matrix, 'travis/model/build/matrix' autoload :Metrics, 'travis/model/build/metrics' autoload :ResultMessage, 'travis/model/build/result_message' autoload :States, 'travis/model/build/states' include Matrix, States, SimpleStates include Travis::Model::EnvHelpers belongs_to :commit belongs_to :request belongs_to :repository, autosave: true belongs_to :owner, polymorphic: true has_many :matrix, as: :source, order: :id, class_name: 'Job::Test', dependent: :destroy has_many :events, as: :source validates :repository_id, :commit_id, :request_id, presence: true serialize :config delegate :same_repo_pull_request?, :to => :request class << self def recent(options = {}) where('state IN (?)', state_names - [:created, :queued]).order(arel_table[:started_at].desc).paged(options) end def was_started where('state <> ?', :created) end def finished where(state: [:finished, :passed, :failed, :errored, :canceled]) # TODO extract end def on_state(state) where(state.present? ? ['builds.state IN (?)', state] : []) end def on_branch(branch) if Build.column_names.include?('branch') pushes.where(branch.present? ? ['branch IN (?)', normalize_to_array(branch)] : []) else pushes.joins(:commit).where(branch.present? ? ['commits.branch IN (?)', normalize_to_array(branch)] : []) end end def by_event_type(event_type) event_type == 'pull_request' ? pull_requests : pushes end def pushes where(:event_type => 'push') end def pull_requests where(event_type: 'pull_request') end def previous(build) where('builds.repository_id = ? AND builds.id < ?', build.repository_id, build.id).finished.descending.limit(1).first end def descending order(arel_table[:id].desc) end def paged(options) page = (options[:page] || 1).to_i limit(per_page).offset(per_page * (page - 1)) end def last_build_on(options) scope = descending scope = scope.on_state(options[:state]) if options[:state] scope = scope.on_branch(options[:branch]) if options[:branch] scope.first end def last_state_on(options) last_build_on(options).try(:state).try(:to_sym) end def older_than(build = nil) scope = descending.paged({}) # TODO in which case we'd call older_than without an argument? scope = scope.where('number::integer < ?', (build.is_a?(Build) ? build.number : build).to_i) if build scope end def next_number maximum(floor('number')).to_i + 1 end protected def normalize_to_array(object) Array(object).compact.join(',').split(',') end def per_page 25 end end after_initialize do self.config = {} if config.nil? end # set the build number and expand the matrix before_create do self.number = repository.builds.next_number self.previous_state = last_finished_state_on_branch self.event_type = request.event_type self.pull_request_title = request.pull_request_title self.pull_request_number = request.pull_request_number self.branch = commit.branch if Build.column_names.include?('branch') expand_matrix end def secure_env_enabled? !pull_request? || same_repo_pull_request? end alias addons_enabled? secure_env_enabled? # sometimes the config is not deserialized and is returned # as a string, this is a work around for now :( def config deserialized = self['config'] if deserialized.is_a?(String) logger.warn "Attribute config isn't YAML. Current serialized attributes: #{Build.serialized_attributes}" deserialized = YAML.load(deserialized) end deserialized end def config=(config) super(config ? normalize_config(config) : {}) end def obfuscated_config config.dup.tap do |config| config.delete(:source_key) next unless config[:env] config[:env] = [config[:env]] unless config[:env].is_a?(Array) if config[:env] config[:env] = config[:env].map do |env| env = normalize_env_hashes(env) obfuscate_env(env).join(' ') end end end end def normalize_env_hashes(lines) if Travis::Features.feature_active?(:global_env_in_config) process_line = ->(line) do if line.is_a?(Hash) env_hash_to_string(line) elsif line.is_a?(Array) line.map do |line| env_hash_to_string(line) end else line end end if lines.is_a?(Array) lines.map { |env| process_line.(env) } else process_line.(lines) end else # TODO: remove this branch when all workers are capable of handling global env if lines.is_a?(Hash) env_hash_to_string(lines) elsif lines.is_a?(Array) lines.map do |line| env_hash_to_string(line) end else lines end end end def env_hash_to_string(hash) return hash unless hash.is_a?(Hash) return hash if hash.has_key?(:secure) hash.map { |k,v| "#{k}=#{v}" }.join(' ') end def cancelable? matrix_finished? end def pull_request? request.pull_request? end # COMPAT: used in http api v1, deprecate as soon as v1 gets retired def result state.try(:to_sym) == :passed ? 0 : 1 end private def normalize_env_values(values) if Travis::Features.feature_active?(:global_env_in_config) env = values global = nil if env.is_a?(Hash) && (env[:global] || env[:matrix]) global = env[:global] env = env[:matrix] end if env env = [env] unless env.is_a?(Array) env = normalize_env_hashes(env) end if global global = [global] unless global.is_a?(Array) global = normalize_env_hashes(global) end { env: env, global: global } else # TODO: remove this branch when all workers are capable of handling global env global = nil if values.is_a?(Hash) && (values[:global] || values[:matrix]) global = values[:global] values = values[:matrix] end result = if global global = [global] unless global.is_a?(Array) values = [values] unless values.is_a?(Array) values.map do |line| line = [line] unless line.is_a?(Array) (line + global).compact end else values end env = if result.is_a?(Array) result.map { |env| normalize_env_hashes(env) } else normalize_env_hashes(result) end if global global = global.map { |env| normalize_env_hashes(env) } end { env: env, global: global } end end def normalize_config(config) config = config.deep_symbolize_keys if config[:env] result = normalize_env_values(config[:env]) config[:env] = result[:env] key = Travis::Features.feature_active?(:global_env_in_config) ? :global_env : :_global_env config[key] = result[:global] if result[:global] end config end def last_finished_state_on_branch repository.builds.finished.last_state_on(branch: commit.branch) end end if the config can not be deseralized, don't freak out! require 'active_record' require 'core_ext/active_record/base' require 'core_ext/hash/deep_symbolize_keys' require 'simple_states' # Build currently models a central but rather abstract domain entity: the thing # that is triggered by a Github request (service hook ping). # # Build groups a matrix of Job::Test instances, and belongs to a Request (and # thus Commit as well as a Repository). # # A Build is created when its Request was configured (by fetching .travis.yml) # and approved (e.g. not excluded by the configuration). Once a Build is # created it will expand its matrix according to the given configuration and # create the according Job::Test instances. Each Job::Test instance will # trigger a test run remotely (on the worker). Once all Job::Test instances # have finished the Build will be finished as well. # # Each of these state changes (build:created, job:started, job:finished, ...) # will issue events that are listened for by the event handlers contained in # travis/notification. These event handlers then send out various notifications # of various types through email, pusher and irc, archive builds and queue # jobs for the workers. # # Build is split up to several modules: # # * Build - ActiveRecord structure, validations and scopes # * States - state definitions and events # * Denormalize - some state changes denormalize attributes to the build's # repository (e.g. Build#started_at gets propagated to # Repository#last_started_at) # * Matrix - logic related to expanding the build matrix, normalizing # configuration for Job::Test instances, evaluating the # final build result etc. # * Messages - helpers for evaluating human readable result messages # (e.g. "Still Failing") # * Events - helpers that are used by notification handlers (and that # TODO probably should be cleaned up and moved to # travis/notification) class Build < ActiveRecord::Base autoload :Denormalize, 'travis/model/build/denormalize' autoload :Matrix, 'travis/model/build/matrix' autoload :Metrics, 'travis/model/build/metrics' autoload :ResultMessage, 'travis/model/build/result_message' autoload :States, 'travis/model/build/states' include Matrix, States, SimpleStates include Travis::Model::EnvHelpers belongs_to :commit belongs_to :request belongs_to :repository, autosave: true belongs_to :owner, polymorphic: true has_many :matrix, as: :source, order: :id, class_name: 'Job::Test', dependent: :destroy has_many :events, as: :source validates :repository_id, :commit_id, :request_id, presence: true serialize :config delegate :same_repo_pull_request?, :to => :request class << self def recent(options = {}) where('state IN (?)', state_names - [:created, :queued]).order(arel_table[:started_at].desc).paged(options) end def was_started where('state <> ?', :created) end def finished where(state: [:finished, :passed, :failed, :errored, :canceled]) # TODO extract end def on_state(state) where(state.present? ? ['builds.state IN (?)', state] : []) end def on_branch(branch) if Build.column_names.include?('branch') pushes.where(branch.present? ? ['branch IN (?)', normalize_to_array(branch)] : []) else pushes.joins(:commit).where(branch.present? ? ['commits.branch IN (?)', normalize_to_array(branch)] : []) end end def by_event_type(event_type) event_type == 'pull_request' ? pull_requests : pushes end def pushes where(:event_type => 'push') end def pull_requests where(event_type: 'pull_request') end def previous(build) where('builds.repository_id = ? AND builds.id < ?', build.repository_id, build.id).finished.descending.limit(1).first end def descending order(arel_table[:id].desc) end def paged(options) page = (options[:page] || 1).to_i limit(per_page).offset(per_page * (page - 1)) end def last_build_on(options) scope = descending scope = scope.on_state(options[:state]) if options[:state] scope = scope.on_branch(options[:branch]) if options[:branch] scope.first end def last_state_on(options) last_build_on(options).try(:state).try(:to_sym) end def older_than(build = nil) scope = descending.paged({}) # TODO in which case we'd call older_than without an argument? scope = scope.where('number::integer < ?', (build.is_a?(Build) ? build.number : build).to_i) if build scope end def next_number maximum(floor('number')).to_i + 1 end protected def normalize_to_array(object) Array(object).compact.join(',').split(',') end def per_page 25 end end after_initialize do self.config = {} if config.nil? end # set the build number and expand the matrix before_create do self.number = repository.builds.next_number self.previous_state = last_finished_state_on_branch self.event_type = request.event_type self.pull_request_title = request.pull_request_title self.pull_request_number = request.pull_request_number self.branch = commit.branch if Build.column_names.include?('branch') expand_matrix end def secure_env_enabled? !pull_request? || same_repo_pull_request? end alias addons_enabled? secure_env_enabled? # sometimes the config is not deserialized and is returned # as a string, this is a work around for now :( def config deserialized = self['config'] if deserialized.is_a?(String) logger.warn "Attribute config isn't YAML. Current serialized attributes: #{Build.serialized_attributes}" deserialized = YAML.load(deserialized) end deserialized rescue Psych::SyntaxError => e logger.warn "[build id:#{id}] Config could not be de-seralized due to #{e.message}" end def config=(config) super(config ? normalize_config(config) : {}) end def obfuscated_config config.dup.tap do |config| config.delete(:source_key) next unless config[:env] config[:env] = [config[:env]] unless config[:env].is_a?(Array) if config[:env] config[:env] = config[:env].map do |env| env = normalize_env_hashes(env) obfuscate_env(env).join(' ') end end end end def normalize_env_hashes(lines) if Travis::Features.feature_active?(:global_env_in_config) process_line = ->(line) do if line.is_a?(Hash) env_hash_to_string(line) elsif line.is_a?(Array) line.map do |line| env_hash_to_string(line) end else line end end if lines.is_a?(Array) lines.map { |env| process_line.(env) } else process_line.(lines) end else # TODO: remove this branch when all workers are capable of handling global env if lines.is_a?(Hash) env_hash_to_string(lines) elsif lines.is_a?(Array) lines.map do |line| env_hash_to_string(line) end else lines end end end def env_hash_to_string(hash) return hash unless hash.is_a?(Hash) return hash if hash.has_key?(:secure) hash.map { |k,v| "#{k}=#{v}" }.join(' ') end def cancelable? matrix_finished? end def pull_request? request.pull_request? end # COMPAT: used in http api v1, deprecate as soon as v1 gets retired def result state.try(:to_sym) == :passed ? 0 : 1 end private def normalize_env_values(values) if Travis::Features.feature_active?(:global_env_in_config) env = values global = nil if env.is_a?(Hash) && (env[:global] || env[:matrix]) global = env[:global] env = env[:matrix] end if env env = [env] unless env.is_a?(Array) env = normalize_env_hashes(env) end if global global = [global] unless global.is_a?(Array) global = normalize_env_hashes(global) end { env: env, global: global } else # TODO: remove this branch when all workers are capable of handling global env global = nil if values.is_a?(Hash) && (values[:global] || values[:matrix]) global = values[:global] values = values[:matrix] end result = if global global = [global] unless global.is_a?(Array) values = [values] unless values.is_a?(Array) values.map do |line| line = [line] unless line.is_a?(Array) (line + global).compact end else values end env = if result.is_a?(Array) result.map { |env| normalize_env_hashes(env) } else normalize_env_hashes(result) end if global global = global.map { |env| normalize_env_hashes(env) } end { env: env, global: global } end end def normalize_config(config) config = config.deep_symbolize_keys if config[:env] result = normalize_env_values(config[:env]) config[:env] = result[:env] key = Travis::Features.feature_active?(:global_env_in_config) ? :global_env : :_global_env config[key] = result[:global] if result[:global] end config end def last_finished_state_on_branch repository.builds.finished.last_state_on(branch: commit.branch) end end
#!/usr/bin/env ruby # vim:set fileencoding=utf-8: require 'unit_hosting/base' module UnitHosting module Api class VmRecipe attr_accessor :rootpw,:ssh_key,:plan_id attr_accessor :op_user,:op_mail,:user_script,:display_name def initialize @op_user = ENV['USER'] end def load_ssh_key file File::open(file) do |f| @ssh_key = f.read end end def params param = { "rootpw" => @rootpw, "ssh_key" => @ssh_key, "op_user" => @op_user, "op_mail" => @op_mail, "user_script" => @user_script, "plan_id" => @plan_id, "display_name" => @display_name } end end end end fix require unit_hosting -> unit-hosting #!/usr/bin/env ruby # vim:set fileencoding=utf-8: require 'unit-hosting/base' module UnitHosting module Api class VmRecipe attr_accessor :rootpw,:ssh_key,:plan_id attr_accessor :op_user,:op_mail,:user_script,:display_name def initialize @op_user = ENV['USER'] end def load_ssh_key file File::open(file) do |f| @ssh_key = f.read end end def params param = { "rootpw" => @rootpw, "ssh_key" => @ssh_key, "op_user" => @op_user, "op_mail" => @op_mail, "user_script" => @user_script, "plan_id" => @plan_id, "display_name" => @display_name } end end end end
module TraxModel VERSION = '0.0.93' end version bump module TraxModel VERSION = '0.0.94' end
require 'savon' require_relative 'base' Savon.configure do |c| c.env_namespace = :s end begin require 'em-http' HTTPI.adapter = :em_http rescue ArgumentError # Fail silently end module UPnP class ControlPoint class Service < Base # @return [String] UPnP service type, including URN. attr_reader :service_type # @return [String] Service identifier, unique within this service's devices. attr_reader :service_id # @return [URI::HTTP] Service description URL. attr_reader :scpd_url # @return [URI::HTTP] Control URL. attr_reader :control_url # @return [URI::HTTP] Eventing URL. attr_reader :event_sub_url # @return [Hash<String,Array<String>>] attr_reader :actions # @return [URI::HTTP] Base URL for this service's device. attr_reader :device_base_url attr_reader :description # Probably don't need to keep this long-term; just adding for testing. attr_reader :service_state_table def initialize(device_base_url, device_service) @device_base_url = device_base_url if device_service[:controlURL] @control_url = build_url(@device_base_url, device_service[:controlURL]) end if device_service[:eventSubURL] @event_sub_url = build_url(@device_base_url, device_service[:eventSubURL]) end if device_service[:SCPDURL] @scpd_url = build_url(@device_base_url, device_service[:SCPDURL]) @description = get_description(@scpd_url) @service_state_table = if @description[:scpd][:serviceStateTable].is_a? Hash @description[:scpd][:serviceStateTable][:stateVariable] elsif @description[:scpd][:serviceStateTable].is_a? Array @description[:scpd][:serviceStateTable].map do |state| state[:stateVariable] end end @actions = [] if @description[:scpd][:actionList] define_methods_from_actions(@description[:scpd][:actionList][:action]) @soap_client = Savon.client do |wsdl| wsdl.endpoint = @control_url wsdl.namespace = @service_type end end end @service_type = device_service[:serviceType] @service_id = device_service[:serviceId] end private def define_methods_from_actions(action_list) if action_list.is_a? Hash action = action_list define_singleton_method(action[:name].to_sym) do |*params| st = @service_type response = @soap_client.request(:u, action[:name], "xmlns:u" => @service_type) do http.headers['SOAPACTION'] = "#{st}##{action[:name]}" soap.body = params.inject({}) do |result, arg| puts "arg: #{arg}" result[:argument_name] = arg result end end argument = action[:argumentList][:argument] if argument.is_a?(Hash) && argument[:direction] == "out" return_ruby_from_soap(action[:name], response, argument) elsif argument.is_a? Array argument.map do |a| if a[:direction] == "out" return_ruby_from_soap(action[:name], response, a) end end else puts "No args with direction 'out'" end end elsif action_list.is_a? Array action_list.each do |action| =begin in_args_count = action[:argumentList][:argument].find_all do |arg| arg[:direction] == 'in' end.size =end @actions << action define_singleton_method(action[:name].to_sym) do |*params| st = @service_type response = @soap_client.request(:u, action[:name], "xmlns:u" => @service_type) do http.headers['SOAPACTION'] = "#{st}##{action[:name]}" soap.body = params.inject({}) do |result, arg| puts "arg: #{arg}" result[:argument_name] = arg result end end argument = action[:argumentList][:argument] if argument.is_a?(Hash) && argument[:direction] == "out" return_ruby_from_soap(action[:name], response, argument) elsif argument.is_a? Array argument.map do |a| if a[:direction] == "out" return_ruby_from_soap(action[:name], response, a) end end else puts "No args with direction 'out'" end end end end end # Uses the serviceStateTable to look up the output from the SOAP response # for the given action, then converts it to the according Ruby data type. # # @param [String] action_name The name of the SOAP action that was called # for which this will get the response from. # @param [Savon::SOAP::Response] soap_response The response from making # the SOAP call. # @param [Hash] out_argument The Hash that tells out the "out" argument # which tells what data type to return. # @return [Hash] Key will be the "out" argument name as a Symbol and the # key will be the value as its converted Ruby type. def return_ruby_from_soap(action_name, soap_response, out_argument) out_arg_name = out_argument[:name] #puts "out arg name: #{out_arg_name}" related_state_variable = out_argument[:relatedStateVariable] #puts "related state var: #{related_state_variable}" state_variable = @service_state_table.find do |state_var_hash| state_var_hash[:name] == related_state_variable end #puts "state var: #{state_variable}" int_types = %w[ui1 ui2 ui4 i1 i2 i4 in] float_types = %w[r4 r8 number fixed.14.4 float] string_types = %w[char string uuid] true_types = %w[1 true yes] false_types = %w[0 false no] if int_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_i } elsif string_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_s } elsif float_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_f } end end end end end Fix for nil @service_type require 'savon' require_relative 'base' Savon.configure do |c| c.env_namespace = :s end begin require 'em-http' HTTPI.adapter = :em_http rescue ArgumentError # Fail silently end module UPnP class ControlPoint class Service < Base # @return [String] UPnP service type, including URN. attr_reader :service_type # @return [String] Service identifier, unique within this service's devices. attr_reader :service_id # @return [URI::HTTP] Service description URL. attr_reader :scpd_url # @return [URI::HTTP] Control URL. attr_reader :control_url # @return [URI::HTTP] Eventing URL. attr_reader :event_sub_url # @return [Hash<String,Array<String>>] attr_reader :actions # @return [URI::HTTP] Base URL for this service's device. attr_reader :device_base_url attr_reader :description # Probably don't need to keep this long-term; just adding for testing. attr_reader :service_state_table def initialize(device_base_url, device_service) @device_base_url = device_base_url if device_service[:controlURL] @control_url = build_url(@device_base_url, device_service[:controlURL]) end if device_service[:eventSubURL] @event_sub_url = build_url(@device_base_url, device_service[:eventSubURL]) end @service_type = device_service[:serviceType] @service_id = device_service[:serviceId] if device_service[:SCPDURL] @scpd_url = build_url(@device_base_url, device_service[:SCPDURL]) @description = get_description(@scpd_url) @service_state_table = if @description[:scpd][:serviceStateTable].is_a? Hash @description[:scpd][:serviceStateTable][:stateVariable] elsif @description[:scpd][:serviceStateTable].is_a? Array @description[:scpd][:serviceStateTable].map do |state| state[:stateVariable] end end @actions = [] if @description[:scpd][:actionList] define_methods_from_actions(@description[:scpd][:actionList][:action]) @soap_client = Savon.client do |wsdl| wsdl.endpoint = @control_url wsdl.namespace = @service_type end end end end private def define_methods_from_actions(action_list) if action_list.is_a? Hash action = action_list define_singleton_method(action[:name].to_sym) do |*params| st = @service_type response = @soap_client.request(:u, action[:name], "xmlns:u" => @service_type) do http.headers['SOAPACTION'] = "#{st}##{action[:name]}" soap.body = params.inject({}) do |result, arg| puts "arg: #{arg}" result[:argument_name] = arg result end end argument = action[:argumentList][:argument] if argument.is_a?(Hash) && argument[:direction] == "out" return_ruby_from_soap(action[:name], response, argument) elsif argument.is_a? Array argument.map do |a| if a[:direction] == "out" return_ruby_from_soap(action[:name], response, a) end end else puts "No args with direction 'out'" end end elsif action_list.is_a? Array action_list.each do |action| =begin in_args_count = action[:argumentList][:argument].find_all do |arg| arg[:direction] == 'in' end.size =end @actions << action define_singleton_method(action[:name].to_sym) do |*params| st = @service_type ControlPoint.log "soap client: #{@soap_client.inspect}" response = @soap_client.request(:u, action[:name], "xmlns:u" => @service_type) do http.headers['SOAPACTION'] = "#{st}##{action[:name]}" soap.body = params.inject({}) do |result, arg| puts "arg: #{arg}" result[:argument_name] = arg result end end argument = action[:argumentList][:argument] if argument.is_a?(Hash) && argument[:direction] == "out" return_ruby_from_soap(action[:name], response, argument) elsif argument.is_a? Array argument.map do |a| if a[:direction] == "out" return_ruby_from_soap(action[:name], response, a) end end else puts "No args with direction 'out'" end end end end end # Uses the serviceStateTable to look up the output from the SOAP response # for the given action, then converts it to the according Ruby data type. # # @param [String] action_name The name of the SOAP action that was called # for which this will get the response from. # @param [Savon::SOAP::Response] soap_response The response from making # the SOAP call. # @param [Hash] out_argument The Hash that tells out the "out" argument # which tells what data type to return. # @return [Hash] Key will be the "out" argument name as a Symbol and the # key will be the value as its converted Ruby type. def return_ruby_from_soap(action_name, soap_response, out_argument) out_arg_name = out_argument[:name] #puts "out arg name: #{out_arg_name}" related_state_variable = out_argument[:relatedStateVariable] #puts "related state var: #{related_state_variable}" state_variable = @service_state_table.find do |state_var_hash| state_var_hash[:name] == related_state_variable end #puts "state var: #{state_variable}" int_types = %w[ui1 ui2 ui4 i1 i2 i4 in] float_types = %w[r4 r8 number fixed.14.4 float] string_types = %w[char string uuid] true_types = %w[1 true yes] false_types = %w[0 false no] if int_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_i } elsif string_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_s } elsif float_types.include? state_variable[:dataType] { out_arg_name.to_sym => soap_response. hash[:Envelope][:Body]["#{action_name}Response".to_sym][out_arg_name.to_sym].to_f } end end end end end
# encoding: utf-8 require 'uri' require 'nokogiri' module ValidateWebsite class Validator XHTML_PATH = File.join(File.dirname(__FILE__), '..', '..', 'data', 'schemas') HTML5_VALIDATOR_SERVICE = 'http://html5.validator.nu/' attr_reader :original_doc, :body, :dtd, :doc, :namespace, :xsd, :errors ## # @param [Nokogiri::HTML::Document] original_doc # @param [String] The raw HTTP response body of the page def initialize(original_doc, body, opts={}) # TODO: write better code @original_doc = original_doc @body = body @options = opts @dtd = @original_doc.internal_subset init_namespace(@dtd) @errors = [] # XXX: euh? of course its empty... if @errors.empty? if @dtd_uri && @body.match(@dtd_uri.to_s) document = @body.sub(@dtd_uri.to_s, @namespace + '.dtd') else document = @body end @doc = Dir.chdir(XHTML_PATH) do Nokogiri::XML(document) { |cfg| cfg.noent.dtdload.dtdvalid } end # http://www.w3.org/TR/xhtml1-schema/ @xsd = Dir.chdir(XHTML_PATH) do if @namespace && File.exists?(@namespace + '.xsd') Nokogiri::XML::Schema(File.read(@namespace + '.xsd')) end end if @xsd @errors = @xsd.validate(@doc) elsif document =~ /^\<!DOCTYPE html\>/i # TODO: use a local Java, Python parser... write a Ruby HTML5 parser ? # https://bitbucket.org/validator/syntax/src # + http://nokogiri.org/Nokogiri/XML/RelaxNG.html ??? require 'net/http' require 'multipart_body' url = URI.parse(HTML5_VALIDATOR_SERVICE) multipart = MultipartBody.new(:content => document) http = Net::HTTP.new(url.host) headers = { 'Content-Type' => "multipart/form-data; boundary=#{multipart.boundary}", 'Content-Length' => multipart.to_s.bytesize.to_s, } res = http.start {|con| con.post(url.path, multipart.to_s, headers) } @errors = Nokogiri::XML.parse(res.body).css('ol li.error').map(&:content) else # dont have xsd fall back to dtd @doc = Dir.chdir(XHTML_PATH) do Nokogiri::HTML.parse(document) end @errors = @doc.errors end end rescue Nokogiri::XML::SyntaxError => e # http://nokogiri.org/tutorials/ensuring_well_formed_markup.html @errors << e end ## # @return [Boolean] def valid? errors.length == 0 end def errors if @options[:ignore_errors] ignore_re = Regexp.compile @options[:ignore_errors] @errors.reject { |e| ignore_re =~ e } else @errors end end private def init_namespace(dtd) if dtd.system_id dtd_uri = URI.parse(dtd.system_id) if dtd.system_id && dtd_uri.path @dtd_uri = dtd_uri # http://www.w3.org/TR/xhtml1/#dtds @namespace = File.basename(@dtd_uri.path, '.dtd') end end end end end validate_website/validator: code quality # encoding: utf-8 require 'uri' require 'nokogiri' module ValidateWebsite class Validator XHTML_PATH = File.join(File.dirname(__FILE__), '..', '..', 'data', 'schemas') HTML5_VALIDATOR_SERVICE = 'http://html5.validator.nu/' attr_reader :original_doc, :body, :dtd, :doc, :namespace, :xsd, :errors ## # @param [Nokogiri::HTML::Document] original_doc # @param [String] The raw HTTP response body of the page def initialize(original_doc, body, opts={}) @original_doc = original_doc @body = body @options = opts @dtd = @original_doc.internal_subset init_namespace(@dtd) find_errors end ## # @return [Boolean] def valid? errors.length == 0 end def errors if @options[:ignore_errors] ignore_re = Regexp.compile @options[:ignore_errors] @errors.reject { |e| ignore_re =~ e } else @errors end end private def init_namespace(dtd) if dtd.system_id dtd_uri = URI.parse(dtd.system_id) if dtd.system_id && dtd_uri.path @dtd_uri = dtd_uri # http://www.w3.org/TR/xhtml1/#dtds @namespace = File.basename(@dtd_uri.path, '.dtd') end end end def find_errors @errors = [] if @dtd_uri && @body.match(@dtd_uri.to_s) document = @body.sub(@dtd_uri.to_s, @namespace + '.dtd') else document = @body end @doc = Dir.chdir(XHTML_PATH) do Nokogiri::XML(document) { |cfg| cfg.noent.dtdload.dtdvalid } end # http://www.w3.org/TR/xhtml1-schema/ @xsd = Dir.chdir(XHTML_PATH) do if @namespace && File.exists?(@namespace + '.xsd') Nokogiri::XML::Schema(File.read(@namespace + '.xsd')) end end if @xsd @errors = @xsd.validate(@doc) elsif document =~ /^\<!DOCTYPE html\>/i html5_validate(document) else # dont have xsd fall back to dtd @doc = Dir.chdir(XHTML_PATH) do Nokogiri::HTML.parse(document) end @errors = @doc.errors end rescue Nokogiri::XML::SyntaxError => e # http://nokogiri.org/tutorials/ensuring_well_formed_markup.html @errors << e end def html5_validate(document) require 'net/http' require 'multipart_body' url = URI.parse('http://html5.validator.nu/') multipart = MultipartBody.new(:content => document) http = Net::HTTP.new(url.host) headers = { 'Content-Type' => "multipart/form-data; boundary=#{multipart.boundary}", 'Content-Length' => multipart.to_s.bytesize.to_s, } res = http.start {|con| con.post(url.path, multipart.to_s, headers) } @errors = Nokogiri::XML.parse(res.body).css('ol li.error').map(&:content) end end end
module Vcloud module Schema FIREWALL_RULE = { type: Hash, internals: { id: { type: 'string_or_number', required: false}, enabled: { type: 'boolean', required: false}, match_on_translate: { type: 'boolean', required: false}, description: { type: 'string', required: false, allowed_empty: true}, policy: { type: 'enum', required: false, acceptable_values: ['allow', 'drop'] }, source_ip: { type: 'ip_address', required: true }, destination_ip: { type: 'ip_address', required: true }, source_port_range: { type: 'string', required: false }, destination_port_range: { type: 'string', required: false }, enable_logging: { type: 'boolean', required: false }, protocols: { type: 'enum', required: false, acceptable_values: ['tcp', 'udp', 'icmp', 'tcp+udp', 'any']}, } } FIREWALL_SERVICE = { type: Hash, allowed_empty: true, internals: { enabled: { type: 'boolean', required: false}, policy: { type: 'enum', required: false, acceptable_values: ['allow', 'drop'] }, log_default_action: { type: 'boolean', required: false}, firewall_rules: { type: Array, required: false, allowed_empty: true, each_element_is: FIREWALL_RULE } } } EDGE_GATEWAY_SERVICES = { type: 'hash', allowed_empty: false, internals: { gateway: { type: 'string' }, firewall_service: FIREWALL_SERVICE } } end end marking fire_wall service as optional in schema module Vcloud module Schema FIREWALL_RULE = { type: Hash, internals: { id: { type: 'string_or_number', required: false}, enabled: { type: 'boolean', required: false}, match_on_translate: { type: 'boolean', required: false}, description: { type: 'string', required: false, allowed_empty: true}, policy: { type: 'enum', required: false, acceptable_values: ['allow', 'drop'] }, source_ip: { type: 'ip_address', required: true }, destination_ip: { type: 'ip_address', required: true }, source_port_range: { type: 'string', required: false }, destination_port_range: { type: 'string', required: false }, enable_logging: { type: 'boolean', required: false }, protocols: { type: 'enum', required: false, acceptable_values: ['tcp', 'udp', 'icmp', 'tcp+udp', 'any']}, } } FIREWALL_SERVICE = { type: Hash, allowed_empty: true, required: false, internals: { enabled: { type: 'boolean', required: false}, policy: { type: 'enum', required: false, acceptable_values: ['allow', 'drop'] }, log_default_action: { type: 'boolean', required: false}, firewall_rules: { type: Array, required: false, allowed_empty: true, each_element_is: FIREWALL_RULE } } } EDGE_GATEWAY_SERVICES = { type: 'hash', allowed_empty: false, internals: { gateway: { type: 'string' }, firewall_service: FIREWALL_SERVICE } } end end
module VirtualBox # Eases the processes of loading specific files then globbing # the rest from a specified directory. module GlobLoader # Glob requires all ruby files in a directory, optionally loading select # files initially (since others may depend on them). # # @param [String] dir The directory to glob # @param [Array<String>] initial_files Initial files (relative to `dir`) # to load def self.glob_require(dir, initial_files=[]) initial_files.each do |file| require File.expand_path(file, dir) end # Glob require the rest Dir[File.join(dir, "**", "*.rb")].each do |f| require File.expand_path(f) end end end end Downcase loaded files. Fixes oddest bug ever on Windows. module VirtualBox # Eases the processes of loading specific files then globbing # the rest from a specified directory. module GlobLoader # Glob requires all ruby files in a directory, optionally loading select # files initially (since others may depend on them). # # @param [String] dir The directory to glob # @param [Array<String>] initial_files Initial files (relative to `dir`) # to load def self.glob_require(dir, initial_files=[]) # Note: The paths below both are "downcased" because on Windows, some # expand to "c:\" and some expand to "C:\" and cause the same file to # be loaded twice. Uck. initial_files.each do |file| require File.expand_path(file, dir).downcase end # Glob require the rest Dir[File.join(dir, "**", "*.rb")].each do |f| require File.expand_path(f).downcase end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "database_fork" spec.version = '0.0.1' spec.authors = ["the-architect"] spec.email = ["marcel.scherf@epicteams.com"] spec.summary = %q{Fork your database} spec.description = %q{Fork your database} spec.homepage = "http://github.com/" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" end bump version # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "database_fork" spec.version = '0.0.2' spec.authors = ["the-architect"] spec.email = ["marcel.scherf@epicteams.com"] spec.summary = %q{Fork your database} spec.description = %q{Fork your database} spec.homepage = "http://github.com/" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" end
require_relative '../constants' module WavefrontDisplay # # Print human-friendly output. If a command requires a dedicated # handler to format its output, define a method with the same name # as that which fetches the data, in a WavefrontDisplay class, # extending this one. # # We provide #long_output() and #multicolumn() methods to solve # standard formatting problems. To use them, define a do_() method # but rather than printing the output, have it call the method. # class Base include WavefrontCli::Constants attr_reader :data, :options # @param data [Map, Hash, Array] the data returned by the SDK # response. # @param options [Hash] options from docopt # def initialize(data, options = {}) @data = data.is_a?(Map) ? Map(put_id_first(data)) : data @options = options end # find the correct method to deal with the output of the user's # command. # def run(method) if method == 'do_list' run_list elsif method == 'do_search' run_search elsif respond_to?("#{method}_brief") send("#{method}_brief") elsif respond_to?(method) send(method) else long_output end end # Choose the correct list handler. The user can specifiy a long # listing with the --long options. # def run_list if options[:long] do_list else do_list_brief end end # Choose the correct search handler. The user can specifiy a long # listing with the --long options. # def run_search if options[:long] do_search else do_search_brief end end # Display classes can provide a do_method_code() method, which # handles <code> errors when running do_method(). (Code is 404 # etc.) # # @param method [Symbol] the error method we wish to call # def run_error(method) return unless respond_to?(method) send(method) exit 1 end # If the data contains an 'id' key, move it to the start. # def put_id_first(data) data.key?(:id) ? { id: data[:id] }.merge(data) : data end # Default display method for 'describe' and long-list methods. # Wraps around #_two_columns() giving you the chance to modify # @data on the fly # # @param fields [Array[Symbol]] a list of fields you wish to # display. If this is nil, all fields are displayed. # @param modified_data [Hash, Array] lets you modify @data # in-line. If this is truthy, it is used. Passing # modified_data means that any fields parameter is ignored. # def long_output(fields = nil, modified_data = nil) require_relative 'printer/long' puts WavefrontDisplayPrinter::Long.new(data, fields, modified_data) end def multicolumn(*columns) require_relative 'printer/terse' puts WavefrontDisplayPrinter::Terse.new(data, *columns) end # Give it a key-value hash, and it will return the size of the first # column to use when formatting that data. # # @param hash [Hash] the data for which you need a column width # @param pad [Integer] the number of spaces you want between columns # @return [Integer] length of longest key + pad # def key_width(hash = {}, pad = 2) return 0 if hash.keys.empty? hash.keys.map(&:size).max + pad end # return [String] the name of the thing we're operating on, like # 'alert' or 'dashboard'. # def friendly_name self.class.name.split('::').last.gsub(/([a-z])([A-Z])/, '\\1 \\2') .downcase end # The following do_ methods are default handlers called # following their namesake operation in the corresponding # WavefrontCli class. They can be overriden in the inheriting # class. # def do_list long_output end def do_list_brief multicolumn(:id, :name) end def do_import puts "Imported #{friendly_name}." long_output end def do_delete puts "Deleted #{friendly_name} '#{options[:'<id>']}'." end def do_undelete puts "Undeleted #{friendly_name} '#{options[:'<id>']}'." end def do_search_brief display_keys = ([:id] + options[:'<condition>'].map do |c| c.split(/\W/, 2).first.to_sym end).uniq if data.empty? puts 'No matches.' else multicolumn(*display_keys) end end def do_search if data.empty? puts 'No matches.' else long_output end end def do_tag_add puts "Tagged #{friendly_name} '#{options[:'<id>']}'." end def do_tag_delete puts "Deleted tag from #{friendly_name} '#{options[:'<id>']}'." end def do_tag_clear puts "Cleared tags on #{friendly_name} '#{options[:'<id>']}'." end def do_tag_set puts "Set tags on #{friendly_name} '#{options[:'<id>']}'." end def do_tags if data.empty? puts "No tags set on #{friendly_name} '#{options[:'<id>']}'." else data.sort.each { |t| puts t } end end # Modify, in-place, the data structure to remove fields which # we deem not of interest to the user. # # @param keys [Symbol] keys you do not wish to be shown. # @return [Nil] # def drop_fields(*keys) if data.is_a?(Array) data.each { |i| i.delete_if { |k, _v| keys.include?(k.to_sym) } } else data.delete_if { |k, _v| keys.include?(k.to_sym) } end end # Modify, in-place, the data structure to make times # human-readable. Automatically handles second and millisecond # epoch times. Currently only operates on top-level keys. # # param keys [Symbol, Array[Symbol]] the keys you wish to be # turned into readable times. # return [Nil] # def readable_time(*keys) keys.each { |k| data[k] = human_time(data[k]) if data.key?(k) } end # Make a time human-readable. Automatically deals with epoch # seconds and epoch milliseconds # # param t [Integer, String] a timestamp. If it's a string, it is # converted to an int. # param force_utc [Boolean] force output in UTC. Currently only # used for unit tests. # return [String] a human-readable timestamp # def human_time(t, force_utc = false) raise ArgumentError unless t.is_a?(Numeric) || t.is_a?(String) str = t.to_s if str =~ /^\d{13}$/ fmt = '%Q' out_fmt = HUMAN_TIME_FORMAT_MS elsif str =~ /^\d{10}$/ fmt = '%s' out_fmt = HUMAN_TIME_FORMAT else raise ArgumentError end ret = DateTime.strptime(str, fmt).to_time ret = ret.utc if force_utc ret.strftime(out_fmt) end end end "no data" if there's no data require_relative '../constants' module WavefrontDisplay # # Print human-friendly output. If a command requires a dedicated # handler to format its output, define a method with the same name # as that which fetches the data, in a WavefrontDisplay class, # extending this one. # # We provide #long_output() and #multicolumn() methods to solve # standard formatting problems. To use them, define a do_() method # but rather than printing the output, have it call the method. # class Base include WavefrontCli::Constants attr_reader :data, :options # @param data [Map, Hash, Array] the data returned by the SDK # response. # @param options [Hash] options from docopt # def initialize(data, options = {}) @data = data.is_a?(Map) ? Map(put_id_first(data)) : data @options = options end # find the correct method to deal with the output of the user's # command. # def run(method) if method == 'do_list' run_list elsif method == 'do_search' run_search elsif respond_to?("#{method}_brief") send("#{method}_brief") elsif respond_to?(method) send(method) else long_output end end # Choose the correct list handler. The user can specifiy a long # listing with the --long options. # def run_list if options[:long] do_list else do_list_brief end end # Choose the correct search handler. The user can specifiy a long # listing with the --long options. # def run_search if options[:long] do_search else do_search_brief end end # Display classes can provide a do_method_code() method, which # handles <code> errors when running do_method(). (Code is 404 # etc.) # # @param method [Symbol] the error method we wish to call # def run_error(method) return unless respond_to?(method) send(method) exit 1 end # If the data contains an 'id' key, move it to the start. # def put_id_first(data) data.key?(:id) ? { id: data[:id] }.merge(data) : data end # Default display method for 'describe' and long-list methods. # Wraps around #_two_columns() giving you the chance to modify # @data on the fly # # @param fields [Array[Symbol]] a list of fields you wish to # display. If this is nil, all fields are displayed. # @param modified_data [Hash, Array] lets you modify @data # in-line. If this is truthy, it is used. Passing # modified_data means that any fields parameter is ignored. # def long_output(fields = nil, modified_data = nil) if data.empty? || (modified_data && modified_data.empty?) puts 'No data.' else require_relative 'printer/long' puts WavefrontDisplayPrinter::Long.new(data, fields, modified_data) end end def multicolumn(*columns) require_relative 'printer/terse' puts WavefrontDisplayPrinter::Terse.new(data, *columns) end # Give it a key-value hash, and it will return the size of the first # column to use when formatting that data. # # @param hash [Hash] the data for which you need a column width # @param pad [Integer] the number of spaces you want between columns # @return [Integer] length of longest key + pad # def key_width(hash = {}, pad = 2) return 0 if hash.keys.empty? hash.keys.map(&:size).max + pad end # return [String] the name of the thing we're operating on, like # 'alert' or 'dashboard'. # def friendly_name self.class.name.split('::').last.gsub(/([a-z])([A-Z])/, '\\1 \\2') .downcase end # The following do_ methods are default handlers called # following their namesake operation in the corresponding # WavefrontCli class. They can be overriden in the inheriting # class. # def do_list long_output end def do_list_brief multicolumn(:id, :name) end def do_import puts "Imported #{friendly_name}." long_output end def do_delete puts "Deleted #{friendly_name} '#{options[:'<id>']}'." end def do_undelete puts "Undeleted #{friendly_name} '#{options[:'<id>']}'." end def do_search_brief display_keys = ([:id] + options[:'<condition>'].map do |c| c.split(/\W/, 2).first.to_sym end).uniq if data.empty? puts 'No matches.' else multicolumn(*display_keys) end end def do_search if data.empty? puts 'No matches.' else long_output end end def do_tag_add puts "Tagged #{friendly_name} '#{options[:'<id>']}'." end def do_tag_delete puts "Deleted tag from #{friendly_name} '#{options[:'<id>']}'." end def do_tag_clear puts "Cleared tags on #{friendly_name} '#{options[:'<id>']}'." end def do_tag_set puts "Set tags on #{friendly_name} '#{options[:'<id>']}'." end def do_tags if data.empty? puts "No tags set on #{friendly_name} '#{options[:'<id>']}'." else data.sort.each { |t| puts t } end end # Modify, in-place, the data structure to remove fields which # we deem not of interest to the user. # # @param keys [Symbol] keys you do not wish to be shown. # @return [Nil] # def drop_fields(*keys) if data.is_a?(Array) data.each { |i| i.delete_if { |k, _v| keys.include?(k.to_sym) } } else data.delete_if { |k, _v| keys.include?(k.to_sym) } end end # Modify, in-place, the data structure to make times # human-readable. Automatically handles second and millisecond # epoch times. Currently only operates on top-level keys. # # param keys [Symbol, Array[Symbol]] the keys you wish to be # turned into readable times. # return [Nil] # def readable_time(*keys) keys.each { |k| data[k] = human_time(data[k]) if data.key?(k) } end # Make a time human-readable. Automatically deals with epoch # seconds and epoch milliseconds # # param t [Integer, String] a timestamp. If it's a string, it is # converted to an int. # param force_utc [Boolean] force output in UTC. Currently only # used for unit tests. # return [String] a human-readable timestamp # def human_time(t, force_utc = false) raise ArgumentError unless t.is_a?(Numeric) || t.is_a?(String) str = t.to_s if str =~ /^\d{13}$/ fmt = '%Q' out_fmt = HUMAN_TIME_FORMAT_MS elsif str =~ /^\d{10}$/ fmt = '%s' out_fmt = HUMAN_TIME_FORMAT else raise ArgumentError end ret = DateTime.strptime(str, fmt).to_time ret = ret.utc if force_utc ret.strftime(out_fmt) end end end
[Add] AmazonAds (2.2.11) Pod::Spec.new do |s| s.name = "AmazonAds" s.version = "2.2.11" s.summary = "Amazon Ads iOS SDK" s.description = <<-DESC Amazon Ads iOS SDK. DESC s.homepage = "https://developer.amazon.com/public/apis/earn/mobile-ads/ios" s.license = { :type => 'Commercial', :file => 'NOTICE.txt' } s.author = { "Amazon.com, Inc." => "https://developer.amazon.com/public/support/contact/contact-us" } s.platform = :ios s.source = { :http => "https://s3.amazonaws.com/dd-smartads-3rd-party-sdks/AmazonAds/2.2.11/AmazonAds.zip" } s.vendored_frameworks = "AmazonAd.framework" s.frameworks = "AdSupport", "CoreLocation", "SystemConfiguration", "CoreTelephony", "CoreGraphics", "MediaPlayer", "EventKit", "EventKitUI" end
# encoding: utf-8 require 'date' module TTY # A class responsible for shell prompt interactions class Shell # A class representing a shell response class Response VALID_TYPES = [ :boolean, :string, :symbol, :integer, :float, :date, :datetime ] attr_reader :reader private :reader attr_reader :shell private :shell attr_reader :question private :question # Initialize a Response # # @api public def initialize(question, shell = Shell.new) @bool_converter = Conversion::BooleanConverter.new @float_converter = Conversion::FloatConverter.new @range_converter = Conversion::RangeConverter.new @int_converter = Conversion::IntegerConverter.new @question = question @shell = shell @reader = Reader.new(shell) end # Read input from STDIN either character or line # # @param [Symbol] type # # @return [undefined] # # @api public def read(type = nil) question.evaluate_response read_input end # @api private def read_input reader = Reader.new(shell) if question.mask? && question.echo? reader.getc(question.mask) else TTY.terminal.echo(question.echo) do TTY.terminal.raw(question.raw) do if question.raw? reader.readpartial(10) elsif question.character? reader.getc(question.mask) else reader.gets end end end end end # Read answer and cast to String type # # @param [String] error # error to display on failed conversion to string type # # @api public def read_string(error = nil) question.evaluate_response(String(read_input).strip) end # Read answer's first character # # @api public def read_char question.char(true) question.evaluate_response String(read_input).chars.to_a[0] end # Read multiple line answer and cast to String type # # @api public def read_text question.evaluate_response String(read_input) end # Read ansewr and cast to Symbol type # # @api public def read_symbol(error = nil) question.evaluate_response read_input.to_sym end # Read answer from predifined choicse # # @api public def read_choice(type = nil) question.argument(:required) unless question.default? question.evaluate_response read_input end # Read integer value # # @api public def read_int(error = nil) question.evaluate_response(@int_converter.convert(read_input)) end # Read float value # # @api public def read_float(error = nil) question.evaluate_response(@float_converter.convert(read_input)) end # Read regular expression # # @api public def read_regex(error = nil) question.evaluate_response Kernel.send(:Regex, read_input) end # Read range expression # # @api public def read_range question.evaluate_response(@range_converter.convert(read_input)) end # Read date # # @api public def read_date question.evaluate_response Date.parse(read_input) end # Read datetime # # @api public def read_datetime question.evaluate_response DateTime.parse(read_input) end # Read boolean # # @api public def read_bool(error = nil) question.evaluate_response(@bool_converter.convert(read_input)) end # Read file contents # # @api public def read_file(error = nil) question.evaluate_response File.open(File.join(directory, read_input)) end # Read string answer and validate against email regex # # @return [String] # # @api public def read_email question.validate(/^[a-z0-9._%+-]+@([a-z0-9-]+\.)+[a-z]{2,6}$/i) question.prompt(question.statement) if question.error with_exception { read_string } end # Read answer provided on multiple lines # # @api public def read_multiple response = '' loop do value = question.evaluate_response read_input break if !value || value == '' next if value !~ /\S/ response << value end response end # Read password # # @api public def read_password question.echo false question.evaluate_response read_input end # Read a single keypress # # @api public def read_keypress question.echo false question.raw true question.evaluate_response(read_input).tap do |key| raise Interrupt if key == "\x03" # Ctrl-C end end private # Ignore exception # # @api private def with_exception(&block) yield rescue question.error? ? block.call : raise end # @param [Symbol] type # :boolean, :string, :numeric, :array # # @api private def read_type(class_or_name) raise TypeError, "Type #{type} is not valid" if type && !valid_type?(type) case type when :string, ::String read_string when :symbol, ::Symbol read_symbol when :float, ::Float read_float end end def valid_type?(type) self.class::VALID_TYPES.include? type.to_sym end end # Response end # Shell end # TTY Change to use necromancer conversion. # encoding: utf-8 require 'date' module TTY # A class responsible for shell prompt interactions class Shell # A class representing a shell response class Response VALID_TYPES = [ :boolean, :string, :symbol, :integer, :float, :date, :datetime ] attr_reader :reader private :reader attr_reader :shell private :shell attr_reader :question private :question # Initialize a Response # # @api public def initialize(question, shell = Shell.new) @question = question @shell = shell @converter = Necromancer.new @reader = Reader.new(shell) end # Read input from STDIN either character or line # # @param [Symbol] type # # @return [undefined] # # @api public def read(type = nil) question.evaluate_response read_input end # @api private def read_input reader = Reader.new(shell) if question.mask? && question.echo? reader.getc(question.mask) else TTY.terminal.echo(question.echo) do TTY.terminal.raw(question.raw) do if question.raw? reader.readpartial(10) elsif question.character? reader.getc(question.mask) else reader.gets end end end end end # Read answer and cast to String type # # @param [String] error # error to display on failed conversion to string type # # @api public def read_string(error = nil) question.evaluate_response(String(read_input).strip) end # Read answer's first character # # @api public def read_char question.char(true) question.evaluate_response String(read_input).chars.to_a[0] end # Read multiple line answer and cast to String type # # @api public def read_text question.evaluate_response String(read_input) end # Read ansewr and cast to Symbol type # # @api public def read_symbol(error = nil) question.evaluate_response(read_input.to_sym) end # Read answer from predifined choicse # # @api public def read_choice(type = nil) question.argument(:required) unless question.default? question.evaluate_response read_input end # Read integer value # # @api public def read_int(error = nil) response = @converter.convert(read_input).to(:integer) question.evaluate_response(response) end # Read float value # # @api public def read_float(error = nil) response = @converter.convert(read_input).to(:float) question.evaluate_response(response) end # Read regular expression # # @api public def read_regex(error = nil) question.evaluate_response Kernel.send(:Regex, read_input) end # Read range expression # # @api public def read_range response = @converter.convert(read_input).to(:range, strict: true) question.evaluate_response(response) end # Read date # # @api public def read_date response = @converter.convert(read_input).to(:date) question.evaluate_response(response) end # Read datetime # # @api public def read_datetime response = @converter.convert(read_input).to(:datetime) question.evaluate_response(response) end # Read boolean # # @api public def read_bool(error = nil) response = @converter.convert(read_input).to(:boolean, strict: true) question.evaluate_response(response) end # Read file contents # # @api public def read_file(error = nil) question.evaluate_response File.open(File.join(directory, read_input)) end # Read string answer and validate against email regex # # @return [String] # # @api public def read_email question.validate(/^[a-z0-9._%+-]+@([a-z0-9-]+\.)+[a-z]{2,6}$/i) question.prompt(question.statement) if question.error with_exception { read_string } end # Read answer provided on multiple lines # # @api public def read_multiple response = '' loop do value = question.evaluate_response read_input break if !value || value == '' next if value !~ /\S/ response << value end response end # Read password # # @api public def read_password question.echo false question.evaluate_response read_input end # Read a single keypress # # @api public def read_keypress question.echo false question.raw true question.evaluate_response(read_input).tap do |key| raise Interrupt if key == "\x03" # Ctrl-C end end private # Ignore exception # # @api private def with_exception(&block) yield rescue question.error? ? block.call : raise end # @param [Symbol] type # :boolean, :string, :numeric, :array # # @api private def read_type(class_or_name) raise TypeError, "Type #{type} is not valid" if type && !valid_type?(type) case type when :string, ::String read_string when :symbol, ::Symbol read_symbol when :float, ::Float read_float end end def valid_type?(type) self.class::VALID_TYPES.include? type.to_sym end end # Response end # Shell end # TTY
module Tumblargh module Node class Tag < Base def type return @type if defined?(@type) n = name.split(':') if n.size == 2 @type = "#{n.first.camelize.to_sym}Tag" else super end end def name elements[1].text_value end def to_tree return [type, name] end end end end Raise if theres an unclosed block found. Will improve this with debugging in the future. module Tumblargh module Node class Tag < Base def type return @type if defined?(@type) n = name.split(':') if n.size == 2 @type = "#{n.first.camelize.to_sym}Tag" raise "There's an unclosed block somewhere..." if @type == 'BlockTag' @type else super end end def name elements[1].text_value end def to_tree return [type, name] end end end end
# encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 Andreas Schmidt, andreas@de-wiring.net # # Wire module module Wire # (Empty) Base command class BaseCommand # +params+ object and +project+ to operate upon attr_accessor :params, :project # returns the state object def state State.instance end # debugs a single line state def dump_state $log.debug "State: [#{state.to_pretty_s}]" end # +outputs+ writes a message to stdout, in given style # # params: # +type+ 1st column as type, i.e. "model" or "network" or "OK" # +msg+ message to print # +style+ coloring etc, supported: # :plain (default), :err (red), :ok (green) # return # - nil # # :reek:ControlParameter def outputs(type, msg, style = :plain) line = "#{type}> #{msg}" line = line.color(:red) if (style == :err) || (style == :error) line = line.color(:green) if style == :ok line = line.color(:cyan) if style == :ok2 $stdout.puts line end # Issues a warning if we do not run as root. def check_user (ENV['USER'] != 'root') && $log.warn("Not running as root. Make sure user #{ENV['USER']} has sudo configured.") end # retrieve all objects of given +type_name+ in # zone (by +zone_name+) # returns: # [Hash] of model subpart with elements of given type def objects_in_zone(type_name, zone_name) return {} unless @project.element?(type_name) objects = @project.get_element type_name || {} objects.select { |_, data| data[:zone] == zone_name } end # runs the command, according to parameters # loads project into @project, calls run_on_project # (to be defined in subclasses) # params # +params+ command parameter map, example key i.e. "target_dir" def run(params = {}) check_user @params = params target_dir = @params[:target_dir] outputs 'model', "Loading model in #{target_dir}" # load it first begin loader = ProjectYamlLoader.new @project = loader.load_project(target_dir) # try to load state file. state.project = @project handle_state_load run_on_project $log.debug? && pp(@project) handle_state_save rescue => load_execption $stderr.puts "Unable to process project model in #{target_dir}" $log.debug? && puts(load_execption.inspect) $log.debug? && puts(load_execption.backtrace) return false end true end # if the hostip is not in cidr, take netmask # from network entry, add to hostip # params: # +host_ip+ i.e. 192.168.10.1 # +network_data+ network data object, to take netmask from :network element def ensure_hostip_netmask(host_ip, network_data) return host_ip if host_ip =~ /[0-9\.]+\/[0-9]+/ match_data = network_data[:network].match(/[0-9\.]+(\/[0-9]+)/) if match_data && match_data.size >= 2 netmask = match_data[1] $log.debug "Adding netmask #{netmask} to host-ip #{host_ip}" return "#{host_ip}#{netmask}" else $log.error "host-ip #{host_ip} is missing netmask, and none given in network." return host_ip end end private # Save state to state file def handle_state_save # dump state $log.debug? && dump_state state.save rescue => save_exception $stderr.puts "Error saving state, #{save_exception}" $log.debug? && puts(save_exception.inspect) $log.debug? && puts(save_exception.backtrace) end def handle_state_load state.load # dump state $log.debug? && dump_state rescue => load_exception $stderr.puts "Error loading state, #{load_exception}" $log.debug? && puts(load_exception.inspect) $log.debug? && puts(load_exception.backtrace) end end end added readme # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 Andreas Schmidt, andreas@de-wiring.net # # Wire module module Wire # (Empty) Base command class BaseCommand # +params+ object and +project+ to operate upon attr_accessor :params, :project # returns the state object def state State.instance end # debugs a single line state def dump_state $log.debug "State: [#{state.to_pretty_s}]" end # +outputs+ writes a message to stdout, in given style # # params: # +type+ 1st column as type, i.e. "model" or "network" or "OK" # +msg+ message to print # +style+ coloring etc, supported: # :plain (default), :err (red), :ok (green) # return # - nil # # :reek:ControlParameter def outputs(type, msg, style = :plain) line = "#{type}> #{msg}" line = line.color(:red) if (style == :err) || (style == :error) line = line.color(:green) if style == :ok line = line.color(:cyan) if style == :ok2 $stdout.puts line end # Issues a warning if we do not run as root. def check_user (ENV['USER'] != 'root') && $log.warn("Not running as root. Make sure user #{ENV['USER']} has sudo configured.") end # retrieve all objects of given +type_name+ in # zone (by +zone_name+) # returns: # [Hash] of model subpart with elements of given type def objects_in_zone(type_name, zone_name) return {} unless @project.element?(type_name) objects = @project.get_element type_name || {} objects.select { |_, data| data[:zone] == zone_name } end # runs the command, according to parameters # loads project into @project, calls run_on_project # (to be defined in subclasses) # params # +params+ command parameter map, example key i.e. "target_dir" def run(params = {}) check_user @params = params target_dir = @params[:target_dir] outputs 'model', "Loading model in #{target_dir}" # load it first begin loader = ProjectYamlLoader.new @project = loader.load_project(target_dir) # try to load state file. state.project = @project handle_state_load run_on_project $log.debug? && puts(@project.to_yaml) handle_state_save rescue => load_execption $stderr.puts "Unable to process project model in #{target_dir}" $log.debug? && puts(load_execption.inspect) $log.debug? && puts(load_execption.backtrace) return false end true end # if the hostip is not in cidr, take netmask # from network entry, add to hostip # params: # +host_ip+ i.e. 192.168.10.1 # +network_data+ network data object, to take netmask from :network element def ensure_hostip_netmask(host_ip, network_data) return host_ip if host_ip =~ /[0-9\.]+\/[0-9]+/ match_data = network_data[:network].match(/[0-9\.]+(\/[0-9]+)/) if match_data && match_data.size >= 2 netmask = match_data[1] $log.debug "Adding netmask #{netmask} to host-ip #{host_ip}" return "#{host_ip}#{netmask}" else $log.error "host-ip #{host_ip} is missing netmask, and none given in network." return host_ip end end private # Save state to state file def handle_state_save # dump state $log.debug? && dump_state state.save rescue => save_exception $stderr.puts "Error saving state, #{save_exception}" $log.debug? && puts(save_exception.inspect) $log.debug? && puts(save_exception.backtrace) end def handle_state_load state.load # dump state $log.debug? && dump_state rescue => load_exception $stderr.puts "Error loading state, #{load_exception}" $log.debug? && puts(load_exception.inspect) $log.debug? && puts(load_exception.backtrace) end end end
require 'parallel' require 'retriable' require 'terminal-table' require 'thor' require 'tumugi/mixin/listable' module Tumugi module Command class Run include Tumugi::Mixin::Listable def execute(dag, options={}) workers = options[:workers] || Tumugi.config.workers settings = { in_threads: workers } logger = Tumugi.logger Parallel.each(dag.tsort, settings) do |t| logger.info "start: #{t.id}" until t.ready? || t.requires_failed? sleep 1 end if t.completed? t.state = :skipped logger.info "#{t.state}: #{t.id} is already completed" elsif t.requires_failed? t.state = :requires_failed logger.info "#{t.state}: #{t.id} has failed requires task" else logger.info "run: #{t.id}" t.state = :running begin Retriable.retriable retry_options do t.run end rescue => e t.state = :failed logger.info "#{t.state}: #{t.id}" logger.error "#{e.message}" else t.state = :completed logger.info "#{t.state}: #{t.id}" end end end show_result_report(dag) return !dag.tsort.any? { |t| t.state == :failed } end private def retry_options { tries: Tumugi.config.max_retry, base_interval: Tumugi.config.retry_interval, max_interval: Tumugi.config.retry_interval * Tumugi.config.max_retry, max_elapsed_time: Tumugi.config.retry_interval * Tumugi.config.max_retry, multiplier: 1.0, rand_factor: 0.0, on_retry: on_retry } end def on_retry Proc.new do |exception, try, elapsed_time, next_interval| if next_interval Tumugi.logger.error "#{exception.class}: '#{exception.message}' - #{try} tries in #{elapsed_time} seconds and #{next_interval} seconds until the next try." else Tumugi.logger.error "#{exception.class}: '#{exception.message}' - #{try} tries in #{elapsed_time} seconds. Task failed." end end end def show_result_report(dag) headings = ['Task', 'Requires', 'Parameters', 'State'] table = Terminal::Table.new headings: headings do |t| dag.tsort.reverse.map do |task| proxy = task.class.merged_parameter_proxy requires = list(task.requires).map do |r| r.id end params = proxy.params.map do |name, _| "#{name}=#{task.send(name.to_sym)}" end t << [ task.id, requires.join("\n"), params.join("\n"), task.state ] end end Tumugi.logger.info "Result report:\n#{table.to_s}" end end end end Show backtrace when command failed require 'parallel' require 'retriable' require 'terminal-table' require 'thor' require 'tumugi/mixin/listable' module Tumugi module Command class Run include Tumugi::Mixin::Listable def execute(dag, options={}) workers = options[:workers] || Tumugi.config.workers settings = { in_threads: workers } logger = Tumugi.logger Parallel.each(dag.tsort, settings) do |t| logger.info "start: #{t.id}" until t.ready? || t.requires_failed? sleep 1 end if t.completed? t.state = :skipped logger.info "#{t.state}: #{t.id} is already completed" elsif t.requires_failed? t.state = :requires_failed logger.info "#{t.state}: #{t.id} has failed requires task" else logger.info "run: #{t.id}" t.state = :running begin Retriable.retriable retry_options do t.run end rescue => e t.state = :failed logger.info "#{t.state}: #{t.id}" logger.error "#{e.message}" logger.error e.backtrace.join("\n") else t.state = :completed logger.info "#{t.state}: #{t.id}" end end end show_result_report(dag) return !dag.tsort.any? { |t| t.state == :failed } end private def retry_options { tries: Tumugi.config.max_retry, base_interval: Tumugi.config.retry_interval, max_interval: Tumugi.config.retry_interval * Tumugi.config.max_retry, max_elapsed_time: Tumugi.config.retry_interval * Tumugi.config.max_retry, multiplier: 1.0, rand_factor: 0.0, on_retry: on_retry } end def on_retry Proc.new do |exception, try, elapsed_time, next_interval| if next_interval Tumugi.logger.error "#{exception.class}: '#{exception.message}' - #{try} tries in #{elapsed_time} seconds and #{next_interval} seconds until the next try." else Tumugi.logger.error "#{exception.class}: '#{exception.message}' - #{try} tries in #{elapsed_time} seconds. Task failed." end end end def show_result_report(dag) headings = ['Task', 'Requires', 'Parameters', 'State'] table = Terminal::Table.new headings: headings do |t| dag.tsort.reverse.map do |task| proxy = task.class.merged_parameter_proxy requires = list(task.requires).map do |r| r.id end params = proxy.params.map do |name, _| "#{name}=#{task.send(name.to_sym)}" end t << [ task.id, requires.join("\n"), params.join("\n"), task.state ] end end Tumugi.logger.info "Result report:\n#{table.to_s}" end end end end
module Turn # Configure Turn def self.config(&block) @config ||= Configuration.new block.call(@config) if block @config end # TODO: Support for test run loggging ? # Central interface for Turn configuration. # class Configuration # List of if file names or glob pattern of tests to run. attr_reader :tests # List of file names or globs to exclude from +tests+ list. attr_reader :exclude # Regexp pattern that all test name's must # match to be eligible to run. attr_accessor :pattern # Regexp pattern that all test cases must # match to be eligible to run. attr_accessor :matchcase # Add these folders to the $LOAD_PATH. attr_reader :loadpath # Libs to require when running tests. attr_reader :requires # Reporter type. attr_accessor :format # Run mode. attr_accessor :runmode # Test against live install (i.e. Don't use loadpath option) attr_accessor :live # Log results? May be true/false or log file name. (TODO) attr_accessor :log # Verbose output? attr_accessor :verbose # Test framework, either :minitest or :testunit attr_accessor :framework # Enable full backtrace attr_accessor :trace # Use natural language case names. attr_accessor :natural # def verbose? @verbose end def live? @live end def natural? @natural end def ansi? @ansi end private def initialize yield(self) if block_given? initialize_defaults end # def initialize_defaults @loadpath ||= ['lib'] @tests ||= ["test/**/{test,}*{,test}.rb"] @exclude ||= [] @requires ||= [] @live ||= false @log ||= true #@format ||= nil #@runner ||= RUBY_VERSION >= "1.9" ? MiniRunner : TestRunner @matchcase ||= nil @pattern ||= /.*/ @natural ||= false @trace ||= environment_trace @ansi ||= environment_ansi @files = nil # reset files just in case end # Collect test configuation. #def test_configuration(options={}) # #options = configure_options(options, 'test') # #options['loadpath'] ||= metadata.loadpath # options['tests'] ||= self.tests # options['loadpath'] ||= self.loadpath # options['requires'] ||= self.requires # options['live'] ||= self.live # options['exclude'] ||= self.exclude # #options['tests'] = list_option(options['tests']) # options['loadpath'] = list_option(options['loadpath']) # options['exclude'] = list_option(options['exclude']) # options['require'] = list_option(options['require']) # return options #end # def list_option(list) case list when nil [] when Array list else list.split(/[:;]/) end end public def ansi=(boolean) @ansi = boolean ? true : false end def tests=(paths) @tests = list_option(paths) end def loadpath=(paths) @loadpath = list_option(paths) end def exclude=(paths) @exclude = list_option(paths) end def requires=(paths) @requires = list_option(paths) end # Test files. def files @files ||= ( fs = tests.map do |t| File.directory?(t) ? Dir[File.join(t, '**', '*')] : Dir[t] end fs = fs.flatten.reject{ |f| File.directory?(f) } ex = exclude.map do |x| File.directory?(x) ? Dir[File.join(x, '**', '*')] : Dir[x] end ex = ex.flatten.reject{ |f| File.directory?(f) } (fs - ex).uniq.map{ |f| File.expand_path(f) } ).flatten end # TODO: Better name ? def suite_name files.map{ |path| File.dirname(path).sub(Dir.pwd+'/','') }.uniq.join(',') end # Select reporter based on output mode. def reporter @reporter ||= ( opts = { :trace=>trace, :natural=>natural? } case format when :marshal require 'turn/reporters/marshal_reporter' Turn::MarshalReporter.new($stdout, opts) when :progress require 'turn/reporters/progress_reporter' Turn::ProgressReporter.new($stdout, opts) when :dotted, :dot require 'turn/reporters/dot_reporter' Turn::DotReporter.new($stdout, opts) when :pretty require 'turn/reporters/pretty_reporter' Turn::PrettyReporter.new($stdout, opts) when :cue require 'turn/reporters/cue_reporter' Turn::CueReporter.new($stdout, opts) else require 'turn/reporters/outline_reporter' Turn::OutlineReporter.new($stdout, opts) end ) end # def environment_trace (ENV['backtrace'] ? ENV['backtrace'].to_i : nil) end # def environment_ansi case ENV['ansi'] when 'true','yes','on' true when 'false','no','off' false else nil end end end end Default to pretty reporter and handle 'rpt' environment variable. module Turn # Configure Turn def self.config(&block) @config ||= Configuration.new block.call(@config) if block @config end # TODO: Support for test run loggging ? # Central interface for Turn configuration. # class Configuration # List of if file names or glob pattern of tests to run. attr_reader :tests # List of file names or globs to exclude from +tests+ list. attr_reader :exclude # Regexp pattern that all test name's must # match to be eligible to run. attr_accessor :pattern # Regexp pattern that all test cases must # match to be eligible to run. attr_accessor :matchcase # Add these folders to the $LOAD_PATH. attr_reader :loadpath # Libs to require when running tests. attr_reader :requires # Reporter type. attr_accessor :format # Run mode. attr_accessor :runmode # Test against live install (i.e. Don't use loadpath option) attr_accessor :live # Log results? May be true/false or log file name. (TODO) attr_accessor :log # Verbose output? attr_accessor :verbose # Test framework, either :minitest or :testunit attr_accessor :framework # Enable full backtrace attr_accessor :trace # Use natural language case names. attr_accessor :natural # def verbose? @verbose end def live? @live end def natural? @natural end def ansi? @ansi end private def initialize yield(self) if block_given? initialize_defaults end # def initialize_defaults @loadpath ||= ['lib'] @tests ||= ["test/**/{test,}*{,test}.rb"] @exclude ||= [] @requires ||= [] @live ||= false @log ||= true #@runner ||= RUBY_VERSION >= "1.9" ? MiniRunner : TestRunner @matchcase ||= nil @pattern ||= /.*/ @natural ||= false @format ||= environment_format @trace ||= environment_trace @ansi ||= environment_ansi @files = nil # reset files just in case end # Collect test configuation. #def test_configuration(options={}) # #options = configure_options(options, 'test') # #options['loadpath'] ||= metadata.loadpath # options['tests'] ||= self.tests # options['loadpath'] ||= self.loadpath # options['requires'] ||= self.requires # options['live'] ||= self.live # options['exclude'] ||= self.exclude # #options['tests'] = list_option(options['tests']) # options['loadpath'] = list_option(options['loadpath']) # options['exclude'] = list_option(options['exclude']) # options['require'] = list_option(options['require']) # return options #end # def list_option(list) case list when nil [] when Array list else list.split(/[:;]/) end end public def ansi=(boolean) @ansi = boolean ? true : false end def tests=(paths) @tests = list_option(paths) end def loadpath=(paths) @loadpath = list_option(paths) end def exclude=(paths) @exclude = list_option(paths) end def requires=(paths) @requires = list_option(paths) end # Test files. def files @files ||= ( fs = tests.map do |t| File.directory?(t) ? Dir[File.join(t, '**', '*')] : Dir[t] end fs = fs.flatten.reject{ |f| File.directory?(f) } ex = exclude.map do |x| File.directory?(x) ? Dir[File.join(x, '**', '*')] : Dir[x] end ex = ex.flatten.reject{ |f| File.directory?(f) } (fs - ex).uniq.map{ |f| File.expand_path(f) } ).flatten end # TODO: Better name ? def suite_name files.map{ |path| File.dirname(path).sub(Dir.pwd+'/','') }.uniq.join(',') end # Select reporter based on output mode. def reporter @reporter ||= ( opts = { :trace=>trace, :natural=>natural? } case format when :marshal require 'turn/reporters/marshal_reporter' Turn::MarshalReporter.new($stdout, opts) when :progress require 'turn/reporters/progress_reporter' Turn::ProgressReporter.new($stdout, opts) when :dotted, :dot require 'turn/reporters/dot_reporter' Turn::DotReporter.new($stdout, opts) when :pretty require 'turn/reporters/pretty_reporter' Turn::PrettyReporter.new($stdout, opts) when :cue require 'turn/reporters/cue_reporter' Turn::CueReporter.new($stdout, opts) else require 'turn/reporters/pretty_reporter' Turn::OutlineReporter.new($stdout, opts) end ) end # def environment_format ENV['rpt'] end # def environment_trace (ENV['backtrace'] ? ENV['backtrace'].to_i : nil) end # def environment_ansi case ENV['ansi'] when 'true','yes','on' true when 'false','no','off' false else nil end end end end
# coding: utf-8 # ウィンドウシステム module WS K_CTRL = 256 # すべての基本、コントロールのクラス class WSControl < Sprite attr_accessor :parent, :font, :width, :height, :resizable_width, :resizable_height attr_accessor :min_width, :min_height, :focusable, :active @@default_font = Font.new(16) def initialize(tx, ty, width, height) super(tx, ty) @width, @height = width, height @min_width, @min_height = 16, 16 self.collision = [0, 0, width - 1, height - 1] @signal_handler = {} # シグナルハンドラ @key_handler = {} # キーハンドラ @hit_cursor = Sprite.new # 衝突判定用スプライト @hit_cursor.collision = [0,0] @font ||= @@default_font @resizable_width = false # オートレイアウト用設定 @resizable_height = false # オートレイアウト用設定 @focusable = false @active = false end # マウスイベント # ユーザはこれをオーバーライドして使う。 # ありがちな処理なら自分で書かなくてもmodule.rbのモジュールをincludeすれば、 # これらをオーバーライドして判定してシグナルを発行してくれるので、 # シグナルを受けるだけでよくなる。 # マウスの左ボタンを押したときに呼ばれる def on_mouse_push(tx, ty) signal(:mouse_push, tx, ty) self end # マウスの左ボタンを離したときに呼ばれる def on_mouse_release(tx, ty) signal(:mouse_release, tx, ty) self end # マウスの中ボタンを押したときに呼ばれる def on_mouse_m_push(tx, ty) signal(:mouse_m_push, tx, ty) self end # マウスの中ボタンを離したときに呼ばれる def on_mouse_m_release(tx, ty) signal(:mouse_m_release, tx, ty) self end # マウスの右ボタンを押したときに呼ばれる def on_mouse_r_push(tx, ty) signal(:mouse_r_push, tx, ty) self end # マウスの右ボタンを離したときに呼ばれる def on_mouse_r_release(tx, ty) signal(:mouse_r_release, tx, ty) self end # マウスカーソルを動かしたときに呼ばれる def on_mouse_move(tx, ty) signal(:mouse_move, tx, ty) self end # コントロールにマウスカーソルが乗ったときに呼ばれる def on_mouse_over signal(:mouse_over) self end # コントロールからマウスカーソルが離れたときに呼ばれる def on_mouse_out signal(:mouse_out) self end # マウスのホイールアップ def on_mouse_wheel_up(tx, ty) signal(:mouse_wheel_up) self end # マウスのホイールダウン def on_mouse_wheel_down(tx, ty) signal(:mouse_wheel_down) self end # マウスイベント用の内部処理 # WSContainerとの協調に必要。特殊なパターンでない限り、ユーザが意識する必要はない。 def mouse_event_dispatch(event, tx, ty) self.__send__(("on_" + event.to_s).to_sym, tx, ty) end # シグナル処理 # add_handlerで登録しておいたMethodオブジェクトもしくはブロックを、signal実行時に呼び出す # 一応、1つのシグナルに複数のハンドラを設定することができるようになっている。はず。 # callを呼ぶのでcallを持っていればそれが呼ばれる。 # シグナルハンドラの登録 def add_handler(signal, obj=nil, &block) if obj if @signal_handler.has_key?(signal) @signal_handler[signal] << obj else @signal_handler[signal] = [obj] end end if block if @signal_handler.has_key?(signal) @signal_handler[signal] << block else @signal_handler[signal] = [block] end end nil end # シグナルの発行(=ハンドラの呼び出し) # ハンドラを呼んだらtrue、何もなければfalseを返す。 def signal(s, *args) if @signal_handler.has_key?(s) @signal_handler[s].each do |obj| obj.call(self, *args) end true else false end end # 絶対座標の算出 def get_global_vertex return [self.x, self.y] unless self.parent tx, ty = self.parent.get_global_vertex [self.x + tx, self.y + ty] end # コントロールの移動/リサイズをするときはmove/resizeを呼ぶ。 # 自分でコントロールのクラスを実装した場合、move/resize時になにか処理が必要なら実装すること。 # :move/:resizeシグナルは外部の処理でこのコントロールのmove/resize後に何かをしたい場合に使う。 # たとえばWSImageを派生クラスを作らず直接newした場合、画像データは外部から設定することになるが、 # resize時に画像の再生成が必要になる。そういうときにこのイベントを捕まえて新しいサイズの画像を生成、設定する。 # :moveシグナルは使い道ないかもしれん。 # コントロールの移動 def move(tx, ty) self.x, self.y = tx, ty signal(:move, tx, ty) nil end # コントロールのリサイズ def resize(width, height) @width, @height = width, height self.collision = [0, 0, width - 1, height - 1] signal(:resize) nil end # キー押したイベント。引数はDXRubyのキー定数。 # ハンドラを呼んだらtrue、何もなければfalseを返す。 def on_key_push(key) result = false key += 256 if Input.key_down?(K_LCONTROL) or Input.key_down?(K_RCONTROL) if @key_handler.has_key?(key) @key_handler[key].each do |obj| obj.call(self) end result ||= true end result end # キー離したイベント。引数はDXRubyのキー定数。 def on_key_release(key) end # キーハンドラ登録 def add_key_handler(key, obj=nil, &block) if obj if @key_handler.has_key?(key) @key_handler[key] << obj else @key_handler[key] = [obj] end end if block if @key_handler.has_key?(key) @key_handler[key] << block else @key_handler[key] = [block] end end nil end # 文字列入力イベント def on_string(str) end # フォーカスが当てられたときに呼ばれる def on_enter @active = true end # フォーカスを失ったときに呼ばれる def on_leave @active = false end # コントロールをアクティブにする def activate self.parent.set_focus(self) if self.focusable self end # アクティブかどうかを返す def activated? @active end # コントロールを読める文字にする def inspect "#<" + self.class.name + ">" end # フォーカスを受け取れるコントロールを配列にして返す def get_focusable_control_ary if @focusable and self.visible [self] else [] end end # フォーカスを受け取れるコントロールを返す def get_focusable_control(tx, ty) if @focusable and self.visible self else nil end end end # 配下にコントロールを保持する機能を追加したコントロール # ウィンドウやリストボックスなど、自身の内部にコントロールを配置するものはWSContainerを使う。 # マウスイベントやdraw/updateの伝播をしてくれる。 # imageにRenderTargetを持ち、配下のオブジェクトのtargetはそれが設定される。 # したがって、配下のオブジェクトの座標は親になるWSContainerの左上隅が0,0となる。 class WSContainer < WSControl attr_accessor :childlen def initialize(tx, ty, width, height) super(tx, ty, width, height) self.image = RenderTarget.new(width, height) # ContainerはRenderTargetを持つ @childlen = [] @layout = nil end # 自身の配下にコントロールを追加する # nameでシンボルを渡されるとその名前でgetterメソッドを追加する def add_control(obj, name=nil) obj.target = self.image # 子コントロールの描画先は親のRenderTargetである obj.parent = self @childlen << obj if name tmp = class << self;self;end tmp.class_eval do define_method(name) do obj end end end obj end # コントロールの削除 def remove_control(obj, name=nil) @childlen.delete(obj) if name tmp = class << self;self;end tmp.class_eval do remove_method(name) end end obj end # Sprite#update時に配下のコントロールにもupdateを投げる def update Sprite.update(@childlen) super end # Sprite#draw時に配下のコントロールにもupdateを投げる def draw Sprite.draw(@childlen) super end # 引数の座標に存在する配下のコントロールを返す。無ければnil def find_hit_object(tx, ty) @hit_cursor.x, @hit_cursor.y = tx, ty @hit_cursor.check(@childlen.reverse)[0] end def mouse_event_dispatch(event, tx, ty) if !WS.captured?(self) or WS.capture_notify # キャプチャしたのが自コンテナだった場合は配下コントロールにイベントを渡さない ctl = find_hit_object(tx, ty) return ctl.mouse_event_dispatch(event, tx - ctl.x, ty - ctl.y) if ctl end super end # オートレイアウト設定開始 def layout(type=nil, &b) @layout = WSLayout.new(type, self, self, &b) @layout.auto_layout end # サイズの変更でRenderTargetをresizeし、オートレイアウトを起動する def resize(width, height) self.image.resize(width, height) if width != @width or height != @height super if @layout @layout.width, @layout.height = width, height @layout.auto_layout end end # フォーカスを受け取れるコントロールを配列にして返す def get_focusable_control_ary return [self] if @focusable and self.visible ary = [] @childlen.each do |o| ary.concat(o.get_focusable_control_ary) end ary end # 座標の位置にあってフォーカスを受け取れるコントロールを返す def get_focusable_control(tx, ty) ctl = find_hit_object(tx, ty) return nil unless ctl return ctl if ctl.focusable return ctl.get_focusable_control(tx - ctl.x, ty - ctl.y) end # コントロールにフォーカスを設定する def set_focus(obj) self.parent.set_focus(obj) if self.parent obj end end # オートレイアウト class WSLayout attr_accessor :type, :x, :y, :width, :height, :resizable_width, :resizable_height, :obj, :parent attr_accessor :margin_left, :margin_right, :margin_top, :margin_bottom attr_accessor :min_width, :min_height def initialize(type, obj, parent, &b) @type, @obj = type, obj @width, @height = parent.width, parent.height @min_width = @min_height = 16 @x = @y = 0 @margin_left = @margin_right = @margin_top = @margin_bottom = 0 @resizable_width = @resizable_height = true @data = [] self.instance_eval &b if b end def layout(type=nil, &b) @data << WSLayout.new(type, @obj, self, &b) self end def add(o, rsw=nil, rsh=nil) @data << o o.resizable_width = rsw if rsw != nil o.resizable_height = rsh if rsh != nil end def adjust_x @data.each do |o| @new_x, @new_y = o.x, o.y @new_width, @new_height = o.width, o.height @new_min_width, @new_min_height = o.min_width, o.min_height yield o # 直交位置サイズ調整 if o.resizable_height # いっぱいに広げる @new_y = self.y + @margin_top @new_height = self.height - @margin_top - @margin_bottom else # 真ん中にする @new_y = (self.height - @margin_top - @margin_bottom) / 2 - @new_height / 2 + self.y + @margin_top end # 変わってたらmoveを呼び出す if @new_x != o.x or @new_y != o.y o.move(@new_x, @new_y) end # 変わってたらresizeを呼び出す if @new_width != o.width or @new_height != o.height o.resize(@new_width, @new_height) end end end def adjust_y @data.each do |o| @new_x, @new_y = o.x, o.y @new_width, @new_height = o.width, o.height @new_min_width, @new_min_height = o.min_width, o.min_height yield o # 直交位置サイズ調整 if o.resizable_width # いっぱいに広げる @new_x = self.x + @margin_left @new_width = self.width - @margin_left - @margin_right else # 真ん中にする @new_x = (self.width - @margin_left - @margin_right) / 2 - @new_width / 2 + self.x + @margin_left end # 変わってたらmoveを呼び出す if @new_x != o.x or @new_y != o.y o.move(@new_x, @new_y) end # 変わってたらresizeを呼び出す if @new_width != o.width or @new_height != o.height o.resize(@new_width, @new_height) end end end def auto_layout case @type when :hbox # 水平に並べる # サイズ未定のものをカウント undef_size_count = @data.count {|o| o.resizable_width } # サイズ確定オブジェクトのサイズ合計 total = @data.inject(0) {|t, o| t += (o.resizable_width ? 0 : o.width)} # 座標開始位置 point = self.x + @margin_left case undef_size_count when 0 # 均等 # 座標調整 adjust_x do |o| tmp = (self.width - @margin_left - @margin_right - total) / (@data.size + 1) # オブジェクトの間隔を足す point += (tmp > 0 ? tmp : 0) @new_x = point point += @new_width end else # 最大化するものを含む # 座標調整 adjust_x do |o| @new_x = point if o.resizable_width # 最大化するオブジェクトを最大化 tmp = (self.width - @margin_left - @margin_right - total) / undef_size_count tmp = @new_min_width if tmp < @new_min_width @new_width = tmp end point += @new_width end end when :vbox # 垂直に並べる # サイズ未定のものをカウント undef_size_count = @data.count {|o| o.resizable_height } # サイズ確定オブジェクトのサイズ合計 total = @data.inject(0) {|t, o| t += (o.resizable_height ? 0 : o.height)} # 座標開始位置 point = self.y + @margin_top case undef_size_count when 0 # 均等 # 座標調整 adjust_y do |o| tmp = (self.height - @margin_top - @margin_bottom - total) / (@data.size + 1) # オブジェクトの間隔を足す point += (tmp > 0 ? tmp : 0) @new_y = point point += @new_height end else # 最大化するものを含む # 座標調整 adjust_y do |o| @new_y = point if o.resizable_height # 最大化するオブジェクトを最大化 tmp = (self.height - @margin_top - @margin_bottom - total) / undef_size_count tmp = @new_min_height if tmp < @new_min_height @new_height = tmp end point += @new_height end end end @data.each do |o| o.auto_layout if WSLayout === o end end def move(tx, ty) @x, @y = tx, ty end def resize(width, height) @width, @height = width, height end def inspect "#<" + self.class.name + ">" end end end class Numeric def clamp(min, max) if self < min min elsif self > max max else self end end end module Input def self.shift? Input.key_down?(K_LSHIFT) or Input.key_down?(K_RSHIFT) end end Enableの処理追加 # coding: utf-8 # ウィンドウシステム module WS K_CTRL = 256 # すべての基本、コントロールのクラス class WSControl < Sprite attr_accessor :parent, :font, :width, :height, :resizable_width, :resizable_height attr_accessor :min_width, :min_height, :focusable, :active, :enable @@default_font = Font.new(16) def initialize(tx, ty, width, height) super(tx, ty) @width, @height = width, height @min_width, @min_height = 16, 16 self.collision = [0, 0, width - 1, height - 1] @signal_handler = {} # シグナルハンドラ @key_handler = {} # キーハンドラ @hit_cursor = Sprite.new # 衝突判定用スプライト @hit_cursor.collision = [0,0] @font ||= @@default_font @resizable_width = false # オートレイアウト用設定 @resizable_height = false # オートレイアウト用設定 @focusable = false @active = false @enable = true end # マウスイベント # ユーザはこれをオーバーライドして使う。 # ありがちな処理なら自分で書かなくてもmodule.rbのモジュールをincludeすれば、 # これらをオーバーライドして判定してシグナルを発行してくれるので、 # シグナルを受けるだけでよくなる。 # マウスの左ボタンを押したときに呼ばれる def on_mouse_push(tx, ty) signal(:mouse_push, tx, ty) self end # マウスの左ボタンを離したときに呼ばれる def on_mouse_release(tx, ty) signal(:mouse_release, tx, ty) self end # マウスの中ボタンを押したときに呼ばれる def on_mouse_m_push(tx, ty) signal(:mouse_m_push, tx, ty) self end # マウスの中ボタンを離したときに呼ばれる def on_mouse_m_release(tx, ty) signal(:mouse_m_release, tx, ty) self end # マウスの右ボタンを押したときに呼ばれる def on_mouse_r_push(tx, ty) signal(:mouse_r_push, tx, ty) self end # マウスの右ボタンを離したときに呼ばれる def on_mouse_r_release(tx, ty) signal(:mouse_r_release, tx, ty) self end # マウスカーソルを動かしたときに呼ばれる def on_mouse_move(tx, ty) signal(:mouse_move, tx, ty) self end # コントロールにマウスカーソルが乗ったときに呼ばれる def on_mouse_over signal(:mouse_over) self end # コントロールからマウスカーソルが離れたときに呼ばれる def on_mouse_out signal(:mouse_out) self end # マウスのホイールアップ def on_mouse_wheel_up(tx, ty) signal(:mouse_wheel_up) self end # マウスのホイールダウン def on_mouse_wheel_down(tx, ty) signal(:mouse_wheel_down) self end # マウスイベント用の内部処理 # WSContainerとの協調に必要。特殊なパターンでない限り、ユーザが意識する必要はない。 def mouse_event_dispatch(event, tx, ty) self.__send__(("on_" + event.to_s).to_sym, tx, ty) end # シグナル処理 # add_handlerで登録しておいたMethodオブジェクトもしくはブロックを、signal実行時に呼び出す # 一応、1つのシグナルに複数のハンドラを設定することができるようになっている。はず。 # callを呼ぶのでcallを持っていればそれが呼ばれる。 # シグナルハンドラの登録 def add_handler(signal, obj=nil, &block) if obj if @signal_handler.has_key?(signal) @signal_handler[signal] << obj else @signal_handler[signal] = [obj] end end if block if @signal_handler.has_key?(signal) @signal_handler[signal] << block else @signal_handler[signal] = [block] end end nil end # シグナルの発行(=ハンドラの呼び出し) # ハンドラを呼んだらtrue、何もなければfalseを返す。 def signal(s, *args) if @signal_handler.has_key?(s) @signal_handler[s].each do |obj| obj.call(self, *args) end true else false end end # 絶対座標の算出 def get_global_vertex return [self.x, self.y] unless self.parent tx, ty = self.parent.get_global_vertex [self.x + tx, self.y + ty] end # コントロールの移動/リサイズをするときはmove/resizeを呼ぶ。 # 自分でコントロールのクラスを実装した場合、move/resize時になにか処理が必要なら実装すること。 # :move/:resizeシグナルは外部の処理でこのコントロールのmove/resize後に何かをしたい場合に使う。 # たとえばWSImageを派生クラスを作らず直接newした場合、画像データは外部から設定することになるが、 # resize時に画像の再生成が必要になる。そういうときにこのイベントを捕まえて新しいサイズの画像を生成、設定する。 # :moveシグナルは使い道ないかもしれん。 # コントロールの移動 def move(tx, ty) self.x, self.y = tx, ty signal(:move, tx, ty) nil end # コントロールのリサイズ def resize(width, height) @width, @height = width, height self.collision = [0, 0, width - 1, height - 1] signal(:resize) nil end # キー押したイベント。引数はDXRubyのキー定数。 # ハンドラを呼んだらtrue、何もなければfalseを返す。 def on_key_push(key) result = false key += 256 if Input.key_down?(K_LCONTROL) or Input.key_down?(K_RCONTROL) if @key_handler.has_key?(key) @key_handler[key].each do |obj| obj.call(self) end result ||= true end result end # キー離したイベント。引数はDXRubyのキー定数。 def on_key_release(key) end # キーハンドラ登録 def add_key_handler(key, obj=nil, &block) if obj if @key_handler.has_key?(key) @key_handler[key] << obj else @key_handler[key] = [obj] end end if block if @key_handler.has_key?(key) @key_handler[key] << block else @key_handler[key] = [block] end end nil end # 文字列入力イベント def on_string(str) end # フォーカスが当てられたときに呼ばれる def on_enter @active = true end # フォーカスを失ったときに呼ばれる def on_leave @active = false end # コントロールをアクティブにする def activate self.parent.set_focus(self) if self.focusable self end # アクティブかどうかを返す def activated? @active end # 有効かどうかを返す def enabled? @enable end # コントロールを読める文字にする def inspect "#<" + self.class.name + ">" end # フォーカスを受け取れるコントロールを配列にして返す def get_focusable_control_ary if @focusable and self.visible and self.enabled? [self] else [] end end # フォーカスを受け取れるコントロールを返す def get_focusable_control(tx, ty) if @focusable and self.visible and self.enabled? self else nil end end end # 配下にコントロールを保持する機能を追加したコントロール # ウィンドウやリストボックスなど、自身の内部にコントロールを配置するものはWSContainerを使う。 # マウスイベントやdraw/updateの伝播をしてくれる。 # imageにRenderTargetを持ち、配下のオブジェクトのtargetはそれが設定される。 # したがって、配下のオブジェクトの座標は親になるWSContainerの左上隅が0,0となる。 class WSContainer < WSControl attr_accessor :childlen def initialize(tx, ty, width, height) super(tx, ty, width, height) self.image = RenderTarget.new(width, height) # ContainerはRenderTargetを持つ @childlen = [] @layout = nil end # 自身の配下にコントロールを追加する # nameでシンボルを渡されるとその名前でgetterメソッドを追加する def add_control(obj, name=nil) obj.target = self.image # 子コントロールの描画先は親のRenderTargetである obj.parent = self @childlen << obj if name tmp = class << self;self;end tmp.class_eval do define_method(name) do obj end end end obj end # コントロールの削除 def remove_control(obj, name=nil) @childlen.delete(obj) if name tmp = class << self;self;end tmp.class_eval do remove_method(name) end end obj end # Sprite#update時に配下のコントロールにもupdateを投げる def update Sprite.update(@childlen) super end # Sprite#draw時に配下のコントロールにもupdateを投げる def draw Sprite.draw(@childlen) super end # 引数の座標に存在する配下のコントロールを返す。無ければnil def find_hit_object(tx, ty) @hit_cursor.x, @hit_cursor.y = tx, ty @hit_cursor.check(@childlen.reverse)[0] end def mouse_event_dispatch(event, tx, ty) if !WS.captured?(self) or WS.capture_notify # キャプチャしたのが自コンテナだった場合は配下コントロールにイベントを渡さない ctl = find_hit_object(tx, ty) return ctl.mouse_event_dispatch(event, tx - ctl.x, ty - ctl.y) if ctl and ctl.enabled? end super end # オートレイアウト設定開始 def layout(type=nil, &b) @layout = WSLayout.new(type, self, self, &b) @layout.auto_layout end # サイズの変更でRenderTargetをresizeし、オートレイアウトを起動する def resize(width, height) self.image.resize(width, height) if width != @width or height != @height super if @layout @layout.width, @layout.height = width, height @layout.auto_layout end end # フォーカスを受け取れるコントロールを配列にして返す def get_focusable_control_ary return [self] if @focusable and self.visible and self.enabled? ary = [] @childlen.each do |o| ary.concat(o.get_focusable_control_ary) end ary end # 座標の位置にあってフォーカスを受け取れるコントロールを返す def get_focusable_control(tx, ty) ctl = find_hit_object(tx, ty) return nil unless ctl return ctl if ctl.focusable and ctl.visible and ctl.enabled? return ctl.get_focusable_control(tx - ctl.x, ty - ctl.y) end # コントロールにフォーカスを設定する def set_focus(obj) self.parent.set_focus(obj) if self.parent obj end end # オートレイアウト class WSLayout attr_accessor :type, :x, :y, :width, :height, :resizable_width, :resizable_height, :obj, :parent attr_accessor :margin_left, :margin_right, :margin_top, :margin_bottom attr_accessor :min_width, :min_height def initialize(type, obj, parent, &b) @type, @obj = type, obj @width, @height = parent.width, parent.height @min_width = @min_height = 16 @x = @y = 0 @margin_left = @margin_right = @margin_top = @margin_bottom = 0 @resizable_width = @resizable_height = true @data = [] self.instance_eval &b if b end def layout(type=nil, &b) @data << WSLayout.new(type, @obj, self, &b) self end def add(o, rsw=nil, rsh=nil) @data << o o.resizable_width = rsw if rsw != nil o.resizable_height = rsh if rsh != nil end def adjust_x @data.each do |o| @new_x, @new_y = o.x, o.y @new_width, @new_height = o.width, o.height @new_min_width, @new_min_height = o.min_width, o.min_height yield o # 直交位置サイズ調整 if o.resizable_height # いっぱいに広げる @new_y = self.y + @margin_top @new_height = self.height - @margin_top - @margin_bottom else # 真ん中にする @new_y = (self.height - @margin_top - @margin_bottom) / 2 - @new_height / 2 + self.y + @margin_top end # 変わってたらmoveを呼び出す if @new_x != o.x or @new_y != o.y o.move(@new_x, @new_y) end # 変わってたらresizeを呼び出す if @new_width != o.width or @new_height != o.height o.resize(@new_width, @new_height) end end end def adjust_y @data.each do |o| @new_x, @new_y = o.x, o.y @new_width, @new_height = o.width, o.height @new_min_width, @new_min_height = o.min_width, o.min_height yield o # 直交位置サイズ調整 if o.resizable_width # いっぱいに広げる @new_x = self.x + @margin_left @new_width = self.width - @margin_left - @margin_right else # 真ん中にする @new_x = (self.width - @margin_left - @margin_right) / 2 - @new_width / 2 + self.x + @margin_left end # 変わってたらmoveを呼び出す if @new_x != o.x or @new_y != o.y o.move(@new_x, @new_y) end # 変わってたらresizeを呼び出す if @new_width != o.width or @new_height != o.height o.resize(@new_width, @new_height) end end end def auto_layout case @type when :hbox # 水平に並べる # サイズ未定のものをカウント undef_size_count = @data.count {|o| o.resizable_width } # サイズ確定オブジェクトのサイズ合計 total = @data.inject(0) {|t, o| t += (o.resizable_width ? 0 : o.width)} # 座標開始位置 point = self.x + @margin_left case undef_size_count when 0 # 均等 # 座標調整 adjust_x do |o| tmp = (self.width - @margin_left - @margin_right - total) / (@data.size + 1) # オブジェクトの間隔を足す point += (tmp > 0 ? tmp : 0) @new_x = point point += @new_width end else # 最大化するものを含む # 座標調整 adjust_x do |o| @new_x = point if o.resizable_width # 最大化するオブジェクトを最大化 tmp = (self.width - @margin_left - @margin_right - total) / undef_size_count tmp = @new_min_width if tmp < @new_min_width @new_width = tmp end point += @new_width end end when :vbox # 垂直に並べる # サイズ未定のものをカウント undef_size_count = @data.count {|o| o.resizable_height } # サイズ確定オブジェクトのサイズ合計 total = @data.inject(0) {|t, o| t += (o.resizable_height ? 0 : o.height)} # 座標開始位置 point = self.y + @margin_top case undef_size_count when 0 # 均等 # 座標調整 adjust_y do |o| tmp = (self.height - @margin_top - @margin_bottom - total) / (@data.size + 1) # オブジェクトの間隔を足す point += (tmp > 0 ? tmp : 0) @new_y = point point += @new_height end else # 最大化するものを含む # 座標調整 adjust_y do |o| @new_y = point if o.resizable_height # 最大化するオブジェクトを最大化 tmp = (self.height - @margin_top - @margin_bottom - total) / undef_size_count tmp = @new_min_height if tmp < @new_min_height @new_height = tmp end point += @new_height end end end @data.each do |o| o.auto_layout if WSLayout === o end end def move(tx, ty) @x, @y = tx, ty end def resize(width, height) @width, @height = width, height end def inspect "#<" + self.class.name + ">" end end end class Numeric def clamp(min, max) if self < min min elsif self > max max else self end end end module Input def self.shift? Input.key_down?(K_LSHIFT) or Input.key_down?(K_RSHIFT) end end
require "rack" require "time" class Cuba class Response attr_accessor :status attr :headers def initialize(status = 200, headers = { "Content-Type" => "text/html; charset=utf-8" }) @status = status @headers = headers @body = [] @length = 0 end def [](key) @headers[key] end def []=(key, value) @headers[key] = value end def write(str) s = str.to_s @length += s.bytesize @headers["Content-Length"] = @length.to_s @body << s end def redirect(path, status = 302) @headers["Location"] = path @status = status end def finish [@status, @headers, @body] end def set_cookie(key, value) Rack::Utils.set_cookie_header!(@headers, key, value) end def delete_cookie(key, value = {}) Rack::Utils.delete_cookie_header!(@headers, key, value) end end def self.reset! @app = nil @prototype = nil end def self.app @app ||= Rack::Builder.new end def self.use(middleware, *args, &block) app.use(middleware, *args, &block) end def self.define(&block) app.run new(&block) end def self.prototype @prototype ||= app.to_app end def self.call(env) prototype.call(env) end def self.plugin(mixin) include mixin extend mixin::ClassMethods if defined?(mixin::ClassMethods) mixin.setup(self) if mixin.respond_to?(:setup) end def self.settings @settings ||= {} end def self.inherited(child) child.settings.replace(settings) end attr :captures def initialize(&blk) @blk = blk @captures = [] end def settings self.class.settings end def call(env) dup.call!(env) end def req Thread.current[:_cuba_req] end def res Thread.current[:_cuba_res] end def env Thread.current[:_cuba_env] end def call!(env) Thread.current[:_cuba_env] = env Thread.current[:_cuba_req] = Rack::Request.new(env) Thread.current[:_cuba_res] = Cuba::Response.new # This `catch` statement will either receive a # rack response tuple via a `halt`, or will # fall back to issuing a 404. # # When it `catch`es a throw, the return value # of this whole `_call` method will be the # rack response tuple, which is exactly what we want. catch(:halt) do instance_eval(&@blk) res.status = 404 res.finish end end def session env["rack.session"] || raise(RuntimeError, "You're missing a session handler. You can get started " + "by adding Cuba.use Rack::Session::Cookie") end # The heart of the path / verb / any condition matching. # # @example # # on get do # res.write "GET" # end # # on get, "signup" do # res.write "Signup # end # # on "user/:id" do |uid| # res.write "User: #{uid}" # end # # on "styles", extension("css") do |file| # res.write render("styles/#{file}.sass") # end # def on(*args, &block) try do # For every block, we make sure to reset captures so that # nesting matchers won't mess with each other's captures. @captures = [] # We stop evaluation of this entire matcher unless # each and every `arg` defined for this matcher evaluates # to a non-false value. # # Short circuit examples: # on true, false do # # # PATH_INFO=/user # on true, "signup" return unless args.all? { |arg| match(arg) } # The captures we yield here were generated and assembled # by evaluating each of the `arg`s above. Most of these # are carried out by #consume. yield(*captures) halt res.finish end end # @private Used internally by #on to ensure that SCRIPT_NAME and # PATH_INFO are reset to their proper values. def try script, path = env["SCRIPT_NAME"], env["PATH_INFO"] yield ensure env["SCRIPT_NAME"], env["PATH_INFO"] = script, path end private :try def consume(pattern) return unless match = env["PATH_INFO"].match(/\A\/(#{pattern})((?:\/|\z))/) path, *vars = match.captures env["SCRIPT_NAME"] += "/#{path}" env["PATH_INFO"] = "#{vars.pop}#{match.post_match}" captures.push(*vars) end private :consume def match(matcher, segment = "([^\\/]+)") case matcher when String then consume(matcher.gsub(/:\w+/, segment)) when Regexp then consume(matcher) when Symbol then consume(segment) when Proc then matcher.call else matcher end end # A matcher for files with a certain extension. # # @example # # PATH_INFO=/style/app.css # on "style", extension("css") do |file| # res.write file # writes app # end def extension(ext = "\\w+") lambda { consume("([^\\/]+?)\.#{ext}\\z") } end # Used to ensure that certain request parameters are present. Acts like a # precondition / assertion for your route. # # @example # # POST with data like user[fname]=John&user[lname]=Doe # on "signup", param("user") do |atts| # User.create(atts) # end def param(key) lambda { captures << req[key] unless req[key].to_s.empty? } end def header(key) lambda { env[key.upcase.tr("-","_")] } end # Useful for matching against the request host (i.e. HTTP_HOST). # # @example # on host("account1.example.com"), "api" do # res.write "You have reached the API of account1." # end def host(hostname) hostname === req.host end # If you want to match against the HTTP_ACCEPT value. # # @example # # HTTP_ACCEPT=application/xml # on accept("application/xml") do # # automatically set to application/xml. # res.write res["Content-Type"] # end def accept(mimetype) lambda do String(env["HTTP_ACCEPT"]).split(",").any? { |s| s.strip == mimetype } and res["Content-Type"] = mimetype end end # Syntactic sugar for providing catch-all matches. # # @example # on default do # res.write "404" # end def default true end # Access the root of the application. # # @example # # # GET / # on root do # res.write "Home" # end def root env["PATH_INFO"] == "/" || env["PATH_INFO"] == "" end # Syntatic sugar for providing HTTP Verb matching. # # @example # on get, "signup" do # end # # on post, "signup" do # end def get; req.get? end def post; req.post? end def put; req.put? end def delete; req.delete? end # If you want to halt the processing of an existing handler # and continue it via a different handler. # # @example # def redirect(*args) # run Cuba.new { on(default) { res.redirect(*args) }} # end # # on "account" do # redirect "/login" unless session["uid"] # # res.write "Super secure account info." # end def run(app) halt app.call(req.env) end def halt(response) throw :halt, response end end Undo threaded context idea. Yes it was a bad idea. Thanks @jano for bringing us back to earth. :-) require "rack" require "time" class Cuba class Response attr_accessor :status attr :headers def initialize(status = 200, headers = { "Content-Type" => "text/html; charset=utf-8" }) @status = status @headers = headers @body = [] @length = 0 end def [](key) @headers[key] end def []=(key, value) @headers[key] = value end def write(str) s = str.to_s @length += s.bytesize @headers["Content-Length"] = @length.to_s @body << s end def redirect(path, status = 302) @headers["Location"] = path @status = status end def finish [@status, @headers, @body] end def set_cookie(key, value) Rack::Utils.set_cookie_header!(@headers, key, value) end def delete_cookie(key, value = {}) Rack::Utils.delete_cookie_header!(@headers, key, value) end end def self.reset! @app = nil @prototype = nil end def self.app @app ||= Rack::Builder.new end def self.use(middleware, *args, &block) app.use(middleware, *args, &block) end def self.define(&block) app.run new(&block) end def self.prototype @prototype ||= app.to_app end def self.call(env) prototype.call(env) end def self.plugin(mixin) include mixin extend mixin::ClassMethods if defined?(mixin::ClassMethods) mixin.setup(self) if mixin.respond_to?(:setup) end def self.settings @settings ||= {} end def self.inherited(child) child.settings.replace(settings) end attr :env attr :req attr :res attr :captures def initialize(&blk) @blk = blk @captures = [] end def settings self.class.settings end def call(env) dup.call!(env) end def call!(env) @env = env @req = Rack::Request.new(env) @res = Cuba::Response.new # This `catch` statement will either receive a # rack response tuple via a `halt`, or will # fall back to issuing a 404. # # When it `catch`es a throw, the return value # of this whole `_call` method will be the # rack response tuple, which is exactly what we want. catch(:halt) do instance_eval(&@blk) res.status = 404 res.finish end end def session env["rack.session"] || raise(RuntimeError, "You're missing a session handler. You can get started " + "by adding Cuba.use Rack::Session::Cookie") end # The heart of the path / verb / any condition matching. # # @example # # on get do # res.write "GET" # end # # on get, "signup" do # res.write "Signup # end # # on "user/:id" do |uid| # res.write "User: #{uid}" # end # # on "styles", extension("css") do |file| # res.write render("styles/#{file}.sass") # end # def on(*args, &block) try do # For every block, we make sure to reset captures so that # nesting matchers won't mess with each other's captures. @captures = [] # We stop evaluation of this entire matcher unless # each and every `arg` defined for this matcher evaluates # to a non-false value. # # Short circuit examples: # on true, false do # # # PATH_INFO=/user # on true, "signup" return unless args.all? { |arg| match(arg) } # The captures we yield here were generated and assembled # by evaluating each of the `arg`s above. Most of these # are carried out by #consume. yield(*captures) halt res.finish end end # @private Used internally by #on to ensure that SCRIPT_NAME and # PATH_INFO are reset to their proper values. def try script, path = env["SCRIPT_NAME"], env["PATH_INFO"] yield ensure env["SCRIPT_NAME"], env["PATH_INFO"] = script, path end private :try def consume(pattern) return unless match = env["PATH_INFO"].match(/\A\/(#{pattern})((?:\/|\z))/) path, *vars = match.captures env["SCRIPT_NAME"] += "/#{path}" env["PATH_INFO"] = "#{vars.pop}#{match.post_match}" captures.push(*vars) end private :consume def match(matcher, segment = "([^\\/]+)") case matcher when String then consume(matcher.gsub(/:\w+/, segment)) when Regexp then consume(matcher) when Symbol then consume(segment) when Proc then matcher.call else matcher end end # A matcher for files with a certain extension. # # @example # # PATH_INFO=/style/app.css # on "style", extension("css") do |file| # res.write file # writes app # end def extension(ext = "\\w+") lambda { consume("([^\\/]+?)\.#{ext}\\z") } end # Used to ensure that certain request parameters are present. Acts like a # precondition / assertion for your route. # # @example # # POST with data like user[fname]=John&user[lname]=Doe # on "signup", param("user") do |atts| # User.create(atts) # end def param(key) lambda { captures << req[key] unless req[key].to_s.empty? } end def header(key) lambda { env[key.upcase.tr("-","_")] } end # Useful for matching against the request host (i.e. HTTP_HOST). # # @example # on host("account1.example.com"), "api" do # res.write "You have reached the API of account1." # end def host(hostname) hostname === req.host end # If you want to match against the HTTP_ACCEPT value. # # @example # # HTTP_ACCEPT=application/xml # on accept("application/xml") do # # automatically set to application/xml. # res.write res["Content-Type"] # end def accept(mimetype) lambda do String(env["HTTP_ACCEPT"]).split(",").any? { |s| s.strip == mimetype } and res["Content-Type"] = mimetype end end # Syntactic sugar for providing catch-all matches. # # @example # on default do # res.write "404" # end def default true end # Access the root of the application. # # @example # # # GET / # on root do # res.write "Home" # end def root env["PATH_INFO"] == "/" || env["PATH_INFO"] == "" end # Syntatic sugar for providing HTTP Verb matching. # # @example # on get, "signup" do # end # # on post, "signup" do # end def get; req.get? end def post; req.post? end def put; req.put? end def delete; req.delete? end # If you want to halt the processing of an existing handler # and continue it via a different handler. # # @example # def redirect(*args) # run Cuba.new { on(default) { res.redirect(*args) }} # end # # on "account" do # redirect "/login" unless session["uid"] # # res.write "Super secure account info." # end def run(app) halt app.call(req.env) end def halt(response) throw :halt, response end end
# frozen_string_literal: true require 'forwardable' require 'json' require 'i18n' require 'tzispa/helpers/provider' require 'tzispa/helpers/sign_requirer' require 'tzispa/utils/string' module Tzispa module Api class ApiException < StandardError; end class UnknownHandlerVerb < ApiException def initialize(s, name) super("Unknown verb: '#{s}' called in api handler '#{name}'") end end class InvalidSign < ApiException; end class Handler include Tzispa::Helpers::Provider include Tzispa::Helpers::SignRequirer extend Forwardable using Tzispa::Utils attr_reader :context, :response_verb, :data, :status def_delegators :@context, :request, :response, :app, :repository, :config, :logger HANDLER_STATUS_UNDEFINED = nil HANDLER_STATUS_OK = :ok HANDLER_MISSING_PARAMETER = :missing_parameter def initialize(context) @context = context end def result(response_verb:, data: nil, status: HANDLER_STATUS_UNDEFINED) @response_verb = response_verb @status = status if status @data = data end def error? status && status != HANDLER_STATUS_OK end def result_json(data, status: nil) result response_verb: :json, data: data, status: status end def result_download(data, status: nil) result response_verb: :download, data: data, status: status end def not_found result response_verb: :not_found end def message I18n.t("#{self.class.name.dottize}.#{status}", default: "#{status}") if status end def run!(verb, predicate=nil) raise UnknownHandlerVerb.new(verb, self.class.name) unless provides? verb raise InvalidSign.new if sign_required? && !sign_valid? # process compound predicates args = predicate ? predicate.split(',') : nil send verb, *args end def set_status(value) @status = value end protected def static_path_sign? context.path_sign? context.router_params[:sign], context.router_params[:handler], context.router_params[:verb], context.router_params[:predicate] end end end end added before hook for api handlers # frozen_string_literal: true require 'forwardable' require 'json' require 'i18n' require 'tzispa/helpers/provider' require 'tzispa/helpers/sign_requirer' require 'tzispa/utils/string' module Tzispa module Api class ApiException < StandardError; end class UnknownHandlerVerb < ApiException def initialize(s, name) super("Unknown verb: '#{s}' called in api handler '#{name}'") end end class InvalidSign < ApiException; end class Handler extend Forwardable include Tzispa::Helpers::Provider include Tzispa::Helpers::SignRequirer using Tzispa::Utils attr_reader :context, :response_verb, :data, :status def_delegators :@context, :request, :response, :app, :repository, :config, :logger, :unauthorized_but_logged HANDLER_STATUS_UNDEFINED = nil HANDLER_STATUS_OK = :ok HANDLER_MISSING_PARAMETER = :missing_parameter def initialize(context) @context = context end def result(response_verb:, data: nil, status: HANDLER_STATUS_UNDEFINED) @response_verb = response_verb @status = status if status @data = data end class << self def before(*args) (@before_chain ||= []).tap do |bef| args.each { |s| s = s.to_sym bef << s unless bef.include?(s) } end end end def error? status && status != HANDLER_STATUS_OK end def result_json(data, status: nil) result response_verb: :json, data: data, status: status end def result_download(data, status: nil) result response_verb: :download, data: data, status: status end def not_found result response_verb: :not_found end def message I18n.t("#{self.class.name.dottize}.#{status}", default: "#{status}") if status end def run!(verb, predicate=nil) raise UnknownHandlerVerb.new(verb, self.class.name) unless provides? verb raise InvalidSign.new if sign_required? && !sign_valid? do_before # process compound predicates args = predicate ? predicate.split(',') : nil send verb, *args end def set_status(value) @status = value end protected def static_path_sign? context.path_sign? context.router_params[:sign], context.router_params[:handler], context.router_params[:verb], context.router_params[:predicate] end def do_before self.class.before.each { |hbef| send hbef } end end end end
include_recipe "hhvm" phpenv_path = "#{node.travis_build_environment.home}/.phpenv" hhvm_path = "#{phpenv_path}/versions/hhvm" directory "#{hhvm_path}/bin" do owner node.travis_build_environment.user group node.travis_build_environment.group action :create recursive true end file "#{hhvm_path}/bin/php" do owner node.travis_build_environment.user group node.travis_build_environment.group mode 00755 content <<-CONTENT #!/usr/bin/env bash hhvm "$@" CONTENT end Install phpunit for HHVM. include_recipe "hhvm" phpenv_path = "#{node.travis_build_environment.home}/.phpenv" hhvm_path = "#{phpenv_path}/versions/hhvm" directory "#{hhvm_path}/bin" do owner node.travis_build_environment.user group node.travis_build_environment.group action :create recursive true end file "#{hhvm_path}/bin/php" do owner node.travis_build_environment.user group node.travis_build_environment.group mode 00755 content <<-CONTENT #!/usr/bin/env bash hhvm "$@" CONTENT end remote_file "#{hhvm_path}/bin/phpunit.phar" do source "https://phar.phpunit.de/phpunit.phar" owner node.travis_build_environment.user group node.travis_build_environment.group end file "#{hhvm_path}/bin/phpunit" do owner node.travis_build_environment.user group node.travis_build_environment.group mode 00755 content <<-CONTENT #!/usr/bin/env bash hhvm "#{hhvm_path}/bin/phpunit.phar" "$@" CONTENT end
module UrlStatus VERSION = "0.1.0" end version bump module UrlStatus VERSION = "0.1.1" end
# Capistrano plugin to manage iptables # # Author: Eric Lindvall <eric@sevenscale.com> # # Usage: # # # Allow web and SSL for app servers # iptables.role :app, 80, 443 # # # Allow ActiveMQ Stomp connections from app instances # iptables.role :activemq, 61613, :from_roles => %w(app) # # # Allow mysql from any app server # iptables.role :db, 3306, :from_roles => %w(app) # Capistrano::Configuration.instance(:must_exist).load do namespace :iptables do def rules @@rules ||= Hash.new { |h,role| h[role] = [] } end namespace :apply do desc "Apply all iptables settings" task :default do tasks.each do |name, task| execute_task(task) unless task == default_task end end end def all(port, options = {}) role(:all, port, options) end def role(role, *ports) options = ports.extract_options! task_opts = role == :all ? {} : { :roles => role } options[:protocol] ||= 'tcp' ports.each do |port| iptables.rules[role.to_sym] << options.merge({ :port => port }) port_description = iptables.rules[role.to_sym].map { |o| "#{o[:port]}/#{o[:protocol]}" }.join(', ') namespace :apply do desc "Allow port #{port_description} in iptables" task role, task_opts do chain_prefix = "#{fetch(:application).upcase}-#{role.to_s.upcase}" chain = "#{chain_prefix[0..23]}-INPUT" iptables.flush(chain) iptables.rules[role.to_sym].each do |rule| iptables.enable(chain, rule[:port], rule[:protocol]) end iptables.save end end end end def enable(chain, port, protocol, options = {}) if from_roles = (options[:from_role] || options[:from_roles]) servers = find_servers(:roles => from_roles, :skip_hostfilter => true).collect do |server| IPSocket.getaddress(server.host) end servers.flatten.uniq.each do |ip_address| sudo %{/sbin/iptables -A #{chain} -p #{protocol} -m #{protocol} -s #{ip_address} --dport #{port} -j ACCEPT} end else sudo %{/sbin/iptables -A #{chain} -p #{protocol} -m #{protocol} --dport #{port} -j ACCEPT} end end def flush(chain) # Create a new chain if it doesn't exist or flush it if it does sudo %{/bin/sh -c "/sbin/iptables -N #{chain} || /sbin/iptables -F #{chain}"} # If this chain isn't jumped to from INPUT, let's make it so sudo %{/bin/sh -c "/sbin/iptables -L INPUT | grep -cq #{chain} || #{sudo} /sbin/iptables -I INPUT -j #{chain}"} end def save sudo %{/etc/rc.d/init.d/iptables save} end end end Make sure the options are being passed to iptables.enable(). # Capistrano plugin to manage iptables # # Author: Eric Lindvall <eric@sevenscale.com> # # Usage: # # # Allow web and SSL for app servers # iptables.role :app, 80, 443 # # # Allow ActiveMQ Stomp connections from app instances # iptables.role :activemq, 61613, :from_roles => %w(app) # # # Allow mysql from any app server # iptables.role :db, 3306, :from_roles => %w(app) # Capistrano::Configuration.instance(:must_exist).load do namespace :iptables do def rules @@rules ||= Hash.new { |h,role| h[role] = [] } end namespace :apply do desc "Apply all iptables settings" task :default do tasks.each do |name, task| execute_task(task) unless task == default_task end end end def all(port, options = {}) role(:all, port, options) end def role(role, *ports) options = ports.extract_options! task_opts = role == :all ? {} : { :roles => role } options[:protocol] ||= 'tcp' ports.each do |port| iptables.rules[role.to_sym] << options.merge({ :port => port }) port_description = iptables.rules[role.to_sym].map { |o| "#{o[:port]}/#{o[:protocol]}" }.join(', ') namespace :apply do desc "Allow port #{port_description} in iptables" task role, task_opts do chain_prefix = "#{fetch(:application).upcase}-#{role.to_s.upcase}" chain = "#{chain_prefix[0..23]}-INPUT" iptables.flush(chain) iptables.rules[role.to_sym].each do |rule| iptables.enable(chain, rule[:port], rule[:protocol], rule) end iptables.save end end end end def enable(chain, port, protocol, options = {}) if from_roles = (options[:from_role] || options[:from_roles]) servers = find_servers(:roles => from_roles, :skip_hostfilter => true).collect do |server| IPSocket.getaddress(server.host) end servers.flatten.uniq.each do |ip_address| sudo %{/sbin/iptables -A #{chain} -p #{protocol} -m #{protocol} -s #{ip_address} --dport #{port} -j ACCEPT} end else sudo %{/sbin/iptables -A #{chain} -p #{protocol} -m #{protocol} --dport #{port} -j ACCEPT} end end def flush(chain) # Create a new chain if it doesn't exist or flush it if it does sudo %{/bin/sh -c "/sbin/iptables -N #{chain} || /sbin/iptables -F #{chain}"} # If this chain isn't jumped to from INPUT, let's make it so sudo %{/bin/sh -c "/sbin/iptables -L INPUT | grep -cq #{chain} || #{sudo} /sbin/iptables -I INPUT -j #{chain}"} end def save sudo %{/etc/rc.d/init.d/iptables save} end end end
name "netuitive-agent" maintainer "Netuitive, Inc" homepage "http://www.netuitive.com" # Defaults to C:/netuitive on Windows # and /opt/netuitive on all other platforms install_dir "#{default_root}/#{name}" build_version '0.5.8-RC1' build_iteration 1 # Creates required build directories dependency "preparation" # netuitive diamond agent dependency "netuitive-diamond" # netuitive statsd dependency "netuitive-statsd" # netuitive event handler dependency "netuitive-event-handler" # Version manifest file dependency "version-manifest" exclude "**/.git" exclude "**/bundler/git" exclude "**/.gitkeep" # main config config_file "#{install_dir}/conf/netuitive-agent.conf" # default collector configs config_file "#{install_dir}/conf/collectors/CassandraJolokiaCollector.conf" config_file "#{install_dir}/conf/collectors/ElasticSearchCollector.conf" config_file "#{install_dir}/conf/collectors/FlumeCollector.conf" config_file "#{install_dir}/conf/collectors/HeartbeatCollector.conf" config_file "#{install_dir}/conf/collectors/HttpCodeCollector.conf" config_file "#{install_dir}/conf/collectors/HttpdCollector.conf" config_file "#{install_dir}/conf/collectors/JolokiaCollector.conf" config_file "#{install_dir}/conf/collectors/KafkaCollector.conf" config_file "#{install_dir}/conf/collectors/KafkaConsumerLagCollector.conf" config_file "#{install_dir}/conf/collectors/KafkaJolokiaCollector.conf" config_file "#{install_dir}/conf/collectors/MongoDBCollector.conf" config_file "#{install_dir}/conf/collectors/MySQLCollector.conf" config_file "#{install_dir}/conf/collectors/NginxCollector.conf" config_file "#{install_dir}/conf/collectors/PostgresqlCollector.conf" config_file "#{install_dir}/conf/collectors/ProcessResourcesCollector.conf" config_file "#{install_dir}/conf/collectors/RabbitMQCollector.conf" config_file "#{install_dir}/conf/collectors/RedisCollector.conf" config_file "#{install_dir}/conf/collectors/SNMPCollector.conf" config_file "#{install_dir}/conf/collectors/SNMPInterfaceCollector.conf" config_file "#{install_dir}/conf/collectors/SolrCollector.conf" config_file "#{install_dir}/conf/collectors/UserScriptsCollector.conf" Version bump to v0.5.8 name "netuitive-agent" maintainer "Netuitive, Inc" homepage "http://www.netuitive.com" # Defaults to C:/netuitive on Windows # and /opt/netuitive on all other platforms install_dir "#{default_root}/#{name}" build_version '0.5.8' build_iteration 1 # Creates required build directories dependency "preparation" # netuitive diamond agent dependency "netuitive-diamond" # netuitive statsd dependency "netuitive-statsd" # netuitive event handler dependency "netuitive-event-handler" # Version manifest file dependency "version-manifest" exclude "**/.git" exclude "**/bundler/git" exclude "**/.gitkeep" # main config config_file "#{install_dir}/conf/netuitive-agent.conf" # default collector configs config_file "#{install_dir}/conf/collectors/CassandraJolokiaCollector.conf" config_file "#{install_dir}/conf/collectors/ElasticSearchCollector.conf" config_file "#{install_dir}/conf/collectors/FlumeCollector.conf" config_file "#{install_dir}/conf/collectors/HeartbeatCollector.conf" config_file "#{install_dir}/conf/collectors/HttpCodeCollector.conf" config_file "#{install_dir}/conf/collectors/HttpdCollector.conf" config_file "#{install_dir}/conf/collectors/JolokiaCollector.conf" config_file "#{install_dir}/conf/collectors/KafkaCollector.conf" config_file "#{install_dir}/conf/collectors/KafkaConsumerLagCollector.conf" config_file "#{install_dir}/conf/collectors/KafkaJolokiaCollector.conf" config_file "#{install_dir}/conf/collectors/MongoDBCollector.conf" config_file "#{install_dir}/conf/collectors/MySQLCollector.conf" config_file "#{install_dir}/conf/collectors/NginxCollector.conf" config_file "#{install_dir}/conf/collectors/PostgresqlCollector.conf" config_file "#{install_dir}/conf/collectors/ProcessResourcesCollector.conf" config_file "#{install_dir}/conf/collectors/RabbitMQCollector.conf" config_file "#{install_dir}/conf/collectors/RedisCollector.conf" config_file "#{install_dir}/conf/collectors/SNMPCollector.conf" config_file "#{install_dir}/conf/collectors/SNMPInterfaceCollector.conf" config_file "#{install_dir}/conf/collectors/SolrCollector.conf" config_file "#{install_dir}/conf/collectors/UserScriptsCollector.conf"
# # Copyright:: Copyright (c) 2012 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "oc-pushy-pedant" version "1.0.4" dependency "libzmq" dependency "ruby" dependency "bundler" dependency "rsync" # TODO: use the public git:// uri once this repo is public source :git => "git@github.com:opscode/oc-pushy-pedant" relative_path "oc-pushy-pedant" build do bundle "install --path=#{install_dir}/embedded/service/gem" command "mkdir -p #{install_dir}/embedded/service/oc-pushy-pedant" command "#{install_dir}/embedded/bin/rsync -a --delete --exclude=.git/*** --exclude=.gitignore ./ #{install_dir}/embedded/service/oc-pushy-pedant/" end Bump oc-pushy-pedant dependency # # Copyright:: Copyright (c) 2012 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "oc-pushy-pedant" version "1.0.5" dependency "libzmq" dependency "ruby" dependency "bundler" dependency "rsync" # TODO: use the public git:// uri once this repo is public source :git => "git@github.com:opscode/oc-pushy-pedant" relative_path "oc-pushy-pedant" build do bundle "install --path=#{install_dir}/embedded/service/gem" command "mkdir -p #{install_dir}/embedded/service/oc-pushy-pedant" command "#{install_dir}/embedded/bin/rsync -a --delete --exclude=.git/*** --exclude=.gitignore ./ #{install_dir}/embedded/service/oc-pushy-pedant/" end
require "pathname" require "vagrant/action/builder" module VagrantPlugins module ProviderKvm module Action # Include the built-in modules so that we can use them as top-level # things. include Vagrant::Action::Builtin # This action boots the VM, assuming the VM is in a state that requires # a bootup (i.e. not saved). def self.action_boot Vagrant::Action::Builder.new.tap do |b| b.use Network b.use Provision b.use Vagrant::Action::Builtin::HandleForwardedPortCollisions if Vagrant::VERSION < "1.4.0" b.use PruneNFSExports b.use NFS b.use PrepareNFSSettings else #FIXME b.use PrepareNFSValidIds b.use SyncedFolderCleanup b.use SyncedFolders b.use PrepareNFSSettings end b.use SetHostname #b.use Customize b.use ForwardPorts b.use Boot if Vagrant::VERSION >= "1.3.0" b.use WaitForCommunicator, [:running] end b.use ShareFolders end end # This is the action that is primarily responsible for completely # freeing the resources of the underlying virtual machine. def self.action_destroy Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use Call, DestroyConfirm do |env2, b3| if env2[:result] b3.use ConfigValidate b3.use EnvSet, :force_halt => true b3.use action_halt if Vagrant::VERSION < "1.4.0" b3.use PruneNFSExports else b3.use PrepareNFSSettings b3.use PrepareNFSValidIds b3.use SyncedFolderCleanup end b3.use Destroy else b3.use MessageWillNotDestroy end end end end end # This is the action that is primarily responsible for halting # the virtual machine, gracefully or by force. def self.action_halt Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env, b2| if env[:result] b2.use Call, IsPaused do |env2, b3| next if !env2[:result] b3.use Resume end b2.use ClearForwardedPorts b2.use Call, GracefulHalt, :shutoff, :running do |env2, b3| if !env2[:result] b3.use ForcedHalt end end else b2.use MessageNotCreated end end end end # This action packages the virtual machine into a single box file. def self.action_package Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use SetupPackageFiles b2.use action_halt if Vagrant::VERSION < "1.4.0" b2.use PruneNFSExports else b2.use PrepareNFSSettings b2.use PrepareNFSValidIds b2.use SyncedFolderCleanup end b2.use Export b2.use PackageVagrantfile b2.use Package end end end # This action just runs the provisioners on the machine. def self.action_provision Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use ConfigValidate b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use Call, IsRunning do |env2, b3| if !env2[:result] b3.use MessageNotRunning next end b3.use Provision end end end end # This action is responsible for reloading the machine, which # brings it down, sucks in new configuration, and brings the # machine back up with the new configuration. def self.action_reload Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use ConfigValidate b2.use action_halt b2.use action_start end end end # This is the action that is primarily responsible for resuming # suspended machines. def self.action_resume Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env, b2| if env[:result] b2.use ResumeNetwork b2.use Resume else b2.use MessageNotCreated end end end end # This is the action that will exec into an SSH shell. def self.action_ssh Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use CheckCreated b.use CheckRunning b.use SSHExec end end # This is the action that will run a single SSH command. def self.action_ssh_run Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use CheckCreated b.use CheckRunning b.use SSHRun end end # This action starts a VM, assuming it is already imported and exists. # A precondition of this action is that the VM exists. def self.action_start Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use ConfigValidate b.use Call, IsRunning do |env, b2| # If the VM is running, then our work here is done, exit next if env[:result] b2.use Call, IsSaved do |env2, b3| if env2[:result] # The VM is saved, so just resume it b3.use action_resume next end b3.use Call, IsPaused do |env3, b4| if env3[:result] b4.use ResumeNetwork b4.use Resume next end # The VM is not saved, so we must have to boot it up # like normal. Boot! b4.use PrepareGui b4.use action_boot end end end end end # This is the action that is primarily responsible for suspending # the virtual machine. def self.action_suspend Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env, b2| if env[:result] b2.use Suspend else b2.use MessageNotCreated end end end end # This action brings the machine up from nothing, including importing # the box, configuring metadata, and booting. def self.action_up Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use SetName b.use ConfigValidate b.use InitStoragePool b.use Call, Created do |env, b2| # If the VM is NOT created yet, then do the setup steps if !env[:result] b2.use CheckBox b2.use SetName b2.use Import b2.use MatchMACAddress end end b.use action_start end end # The autoload farm action_root = Pathname.new(File.expand_path("../action", __FILE__)) autoload :Boot, action_root.join("boot") autoload :CheckBox, action_root.join("check_box") autoload :CheckCreated, action_root.join("check_created") autoload :CheckKvm, action_root.join("check_kvm") autoload :CheckRunning, action_root.join("check_running") autoload :ClearForwardedPorts, action_root.join("clear_forwarded_ports") autoload :Created, action_root.join("created") autoload :Destroy, action_root.join("destroy") autoload :DestroyConfirm, action_root.join("destroy_confirm") autoload :Export, action_root.join("export") autoload :ForcedHalt, action_root.join("forced_halt") autoload :ForwardPorts, action_root.join("forward_ports") autoload :Import, action_root.join("import") autoload :InitStoragePool, action_root.join("init_storage_pool") autoload :IsPaused, action_root.join("is_paused") autoload :IsRunning, action_root.join("is_running") autoload :IsSaved, action_root.join("is_saved") autoload :MatchMACAddress, action_root.join("match_mac_address") autoload :MessageNotCreated, action_root.join("message_not_created") autoload :MessageWillNotDestroy, action_root.join("message_will_not_destroy") autoload :Network, action_root.join("network") autoload :PackageVagrantfile, action_root.join("package_vagrantfile") autoload :Package, action_root.join("package") autoload :PrepareGui, action_root.join("prepare_gui") autoload :PrepareNFSSettings, action_root.join("prepare_nfs_settings") autoload :PrepareNFSValidIds, action_root.join("prepare_nfs_valid_ids") autoload :PruneNFSExports, action_root.join("prune_nfs_exports") autoload :Resume, action_root.join("resume") autoload :ResumeNetwork, action_root.join("resume_network") autoload :SetName, action_root.join("set_name") autoload :SetupPackageFiles, action_root.join("setup_package_files") autoload :ShareFolders, action_root.join("share_folders") autoload :Suspend, action_root.join("suspend") end end end Load MessageNotRunning class on action.rb require "pathname" require "vagrant/action/builder" module VagrantPlugins module ProviderKvm module Action # Include the built-in modules so that we can use them as top-level # things. include Vagrant::Action::Builtin # This action boots the VM, assuming the VM is in a state that requires # a bootup (i.e. not saved). def self.action_boot Vagrant::Action::Builder.new.tap do |b| b.use Network b.use Provision b.use Vagrant::Action::Builtin::HandleForwardedPortCollisions if Vagrant::VERSION < "1.4.0" b.use PruneNFSExports b.use NFS b.use PrepareNFSSettings else #FIXME b.use PrepareNFSValidIds b.use SyncedFolderCleanup b.use SyncedFolders b.use PrepareNFSSettings end b.use SetHostname #b.use Customize b.use ForwardPorts b.use Boot if Vagrant::VERSION >= "1.3.0" b.use WaitForCommunicator, [:running] end b.use ShareFolders end end # This is the action that is primarily responsible for completely # freeing the resources of the underlying virtual machine. def self.action_destroy Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use Call, DestroyConfirm do |env2, b3| if env2[:result] b3.use ConfigValidate b3.use EnvSet, :force_halt => true b3.use action_halt if Vagrant::VERSION < "1.4.0" b3.use PruneNFSExports else b3.use PrepareNFSSettings b3.use PrepareNFSValidIds b3.use SyncedFolderCleanup end b3.use Destroy else b3.use MessageWillNotDestroy end end end end end # This is the action that is primarily responsible for halting # the virtual machine, gracefully or by force. def self.action_halt Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env, b2| if env[:result] b2.use Call, IsPaused do |env2, b3| next if !env2[:result] b3.use Resume end b2.use ClearForwardedPorts b2.use Call, GracefulHalt, :shutoff, :running do |env2, b3| if !env2[:result] b3.use ForcedHalt end end else b2.use MessageNotCreated end end end end # This action packages the virtual machine into a single box file. def self.action_package Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use SetupPackageFiles b2.use action_halt if Vagrant::VERSION < "1.4.0" b2.use PruneNFSExports else b2.use PrepareNFSSettings b2.use PrepareNFSValidIds b2.use SyncedFolderCleanup end b2.use Export b2.use PackageVagrantfile b2.use Package end end end # This action just runs the provisioners on the machine. def self.action_provision Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use ConfigValidate b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use Call, IsRunning do |env2, b3| if !env2[:result] b3.use MessageNotRunning next end b3.use Provision end end end end # This action is responsible for reloading the machine, which # brings it down, sucks in new configuration, and brings the # machine back up with the new configuration. def self.action_reload Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env1, b2| if !env1[:result] b2.use MessageNotCreated next end b2.use ConfigValidate b2.use action_halt b2.use action_start end end end # This is the action that is primarily responsible for resuming # suspended machines. def self.action_resume Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env, b2| if env[:result] b2.use ResumeNetwork b2.use Resume else b2.use MessageNotCreated end end end end # This is the action that will exec into an SSH shell. def self.action_ssh Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use CheckCreated b.use CheckRunning b.use SSHExec end end # This is the action that will run a single SSH command. def self.action_ssh_run Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use CheckCreated b.use CheckRunning b.use SSHRun end end # This action starts a VM, assuming it is already imported and exists. # A precondition of this action is that the VM exists. def self.action_start Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use ConfigValidate b.use Call, IsRunning do |env, b2| # If the VM is running, then our work here is done, exit next if env[:result] b2.use Call, IsSaved do |env2, b3| if env2[:result] # The VM is saved, so just resume it b3.use action_resume next end b3.use Call, IsPaused do |env3, b4| if env3[:result] b4.use ResumeNetwork b4.use Resume next end # The VM is not saved, so we must have to boot it up # like normal. Boot! b4.use PrepareGui b4.use action_boot end end end end end # This is the action that is primarily responsible for suspending # the virtual machine. def self.action_suspend Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use Call, Created do |env, b2| if env[:result] b2.use Suspend else b2.use MessageNotCreated end end end end # This action brings the machine up from nothing, including importing # the box, configuring metadata, and booting. def self.action_up Vagrant::Action::Builder.new.tap do |b| b.use CheckKvm b.use SetName b.use ConfigValidate b.use InitStoragePool b.use Call, Created do |env, b2| # If the VM is NOT created yet, then do the setup steps if !env[:result] b2.use CheckBox b2.use SetName b2.use Import b2.use MatchMACAddress end end b.use action_start end end # The autoload farm action_root = Pathname.new(File.expand_path("../action", __FILE__)) autoload :Boot, action_root.join("boot") autoload :CheckBox, action_root.join("check_box") autoload :CheckCreated, action_root.join("check_created") autoload :CheckKvm, action_root.join("check_kvm") autoload :CheckRunning, action_root.join("check_running") autoload :ClearForwardedPorts, action_root.join("clear_forwarded_ports") autoload :Created, action_root.join("created") autoload :Destroy, action_root.join("destroy") autoload :DestroyConfirm, action_root.join("destroy_confirm") autoload :Export, action_root.join("export") autoload :ForcedHalt, action_root.join("forced_halt") autoload :ForwardPorts, action_root.join("forward_ports") autoload :Import, action_root.join("import") autoload :InitStoragePool, action_root.join("init_storage_pool") autoload :IsPaused, action_root.join("is_paused") autoload :IsRunning, action_root.join("is_running") autoload :IsSaved, action_root.join("is_saved") autoload :MatchMACAddress, action_root.join("match_mac_address") autoload :MessageNotCreated, action_root.join("message_not_created") autoload :MessageNotRunning, action_root.join("message_not_running") autoload :MessageWillNotDestroy, action_root.join("message_will_not_destroy") autoload :Network, action_root.join("network") autoload :PackageVagrantfile, action_root.join("package_vagrantfile") autoload :Package, action_root.join("package") autoload :PrepareGui, action_root.join("prepare_gui") autoload :PrepareNFSSettings, action_root.join("prepare_nfs_settings") autoload :PrepareNFSValidIds, action_root.join("prepare_nfs_valid_ids") autoload :PruneNFSExports, action_root.join("prune_nfs_exports") autoload :Resume, action_root.join("resume") autoload :ResumeNetwork, action_root.join("resume_network") autoload :SetName, action_root.join("set_name") autoload :SetupPackageFiles, action_root.join("setup_package_files") autoload :ShareFolders, action_root.join("share_folders") autoload :Suspend, action_root.join("suspend") end end end
Verbs::Conjugator.conjugations do |conjugate| conjugate.irregular :be do |verb| # copular verb.form :am, :tense => :present, :person => :first, :plurality => :singular verb.form :is, :tense => :present, :person => :third, :plurality => :singular verb.form :are, :tense => :present, :person => :second, :plurality => :singular verb.form :are, :tense => :present, :person => :first, :plurality => :plural verb.form :are, :tense => :present, :person => :third, :plurality => :plural verb.form :was, :tense => :past, :person => :first, :plurality => :singular verb.form :was, :tense => :past, :person => :third, :plurality => :singular verb.form :were, :tense => :past, :person => :second, :plurality => :singular verb.form :were, :tense => :past, :person => :first, :plurality => :plural verb.form :were, :tense => :past, :person => :third, :plurality => :plural verb.form :were, :tense => :past, :mood => :subjunctive verb.form :be, :tense => :present, :mood => :subjunctive verb.form :being, :tense => :present, :derivative => :participle verb.form :been, :tense => :past, :derivative => :participle end conjugate.irregular :have do |verb| verb.form :have, :tense => :present, :person => :first, :plurality => :singular verb.form :has, :tense => :present, :person => :third, :plurality => :singular verb.form :have, :tense => :present, :person => :second, :plurality => :singular verb.form :have, :tense => :present, :person => :first, :plurality => :plural verb.form :have, :tense => :present, :person => :third, :plurality => :plural verb.form :had, :tense => :past, :person => :first, :plurality => :singular verb.form :had, :tense => :past, :person => :third, :plurality => :singular verb.form :had, :tense => :past, :person => :second, :plurality => :singular verb.form :had, :tense => :past, :person => :first, :plurality => :plural verb.form :had, :tense => :past, :person => :third, :plurality => :plural verb.form :having, :tense => :present, :derivative => :participle verb.form :had, :tense => :past, :derivative => :participle end # http://cpansearch.perl.org/src/RWG/Lingua-EN-Conjugate-0.308/lib/Lingua/EN/Conjugate.pm conjugate.irregular :awake, :awoke, :awoken conjugate.irregular :bear, :bore, :born conjugate.irregular :beat, :beat, :beat conjugate.irregular :become, :became, :become conjugate.irregular :begin, :began, :begun conjugate.irregular :bend, :bent, :bent conjugate.irregular :beset, :beset, :beset conjugate.irregular :bet, :bet, :bet conjugate.irregular :bid, :bid, :bid conjugate.irregular :bind, :bound, :bound conjugate.irregular :bite, :bit, :bitten conjugate.irregular :bleed, :bled, :bled conjugate.irregular :blow, :blew, :blown conjugate.irregular :break, :broke, :broken conjugate.irregular :breed, :bred, :bred conjugate.irregular :bring, :brought, :brought conjugate.irregular :broadcast, :broadcast, :broadcast conjugate.irregular :build, :built, :built conjugate.irregular :burn, :burned, :burned conjugate.irregular :burst, :burst, :burst conjugate.irregular :buy, :bought, :bought conjugate.irregular :cast, :cast, :cast conjugate.irregular :catch, :caught, :caught conjugate.irregular :choose, :chose, :chosen conjugate.irregular :cling, :clung, :clung conjugate.irregular :come, :came, :come conjugate.irregular :cost, :cost, :cost conjugate.irregular :creep, :crept, :crept conjugate.irregular :cut, :cut, :cut conjugate.irregular :deal, :dealt, :dealt conjugate.irregular :dig, :dug, :dug conjugate.irregular :dive, :dove, :dived conjugate.irregular 'do', :did, :done conjugate.irregular :draw, :drew, :drawn conjugate.irregular :dream, :dreamed, :dreamed conjugate.irregular :drive, :drove, :driven conjugate.irregular :drink, :drank, :drunk conjugate.irregular :eat, :ate, :eaten conjugate.irregular :fall, :fell, :fallen conjugate.irregular :feed, :fed, :fed conjugate.irregular :feel, :felt, :felt conjugate.irregular :fight, :fought, :fought conjugate.irregular :find, :found, :found conjugate.irregular :fit, :fit, :fit conjugate.irregular :flee, :fled, :fled conjugate.irregular :fling, :flung, :flung conjugate.irregular :fly, :flew, :flown conjugate.irregular :forbid, :forbade, :forbidden conjugate.irregular :forget, :forgot, :forgotten conjugate.irregular :forego, :forewent, :foregone conjugate.irregular :forgo, :forwent, :forgone conjugate.irregular :forgive, :forgave, :forgiven conjugate.irregular :forsake, :forsook, :forsaken conjugate.irregular :freeze, :froze, :frozen conjugate.irregular :get, :got, :gotten conjugate.irregular :give, :gave, :given conjugate.irregular :go, :went, :gone conjugate.irregular :grind, :ground, :ground conjugate.irregular :grow, :grew, :grown conjugate.irregular :hang, :hung, :hung conjugate.irregular :hear, :heard, :heard conjugate.irregular :hide, :hid, :hidden conjugate.irregular :hit, :hit, :hit conjugate.irregular :hold, :held, :held conjugate.irregular :hurt, :hurt, :hurt conjugate.irregular :keep, :kept, :kept conjugate.irregular :kneel, :knelt, :knelt conjugate.irregular :knit, :knit, :knit conjugate.irregular :know, :knew, :known conjugate.irregular :lay, :laid, :laid conjugate.irregular :lead, :led, :led conjugate.irregular :leap, :leaped, :leaped conjugate.irregular :learn, :learned, :learned conjugate.irregular :leave, :left, :left conjugate.irregular :lend, :lent, :lent conjugate.irregular :let, :let, :let conjugate.irregular :lie, :lay, :lain conjugate.irregular :light, :lit, :lighted conjugate.irregular :lose, :lost, :lost conjugate.irregular :make, :made, :made conjugate.irregular :mean, :meant, :meant conjugate.irregular :meet, :met, :met conjugate.irregular :misspell, :misspelled, :misspelled conjugate.irregular :mistake, :mistook, :mistaken conjugate.irregular :mow, :mowed, :mowed conjugate.irregular :overcome, :overcame, :overcome conjugate.irregular :overdo, :overdid, :overdone conjugate.irregular :overtake, :overtook, :overtaken conjugate.irregular :overthrow, :overthrew, :overthrown conjugate.irregular :pay, :paid, :paid conjugate.irregular :plead, :pled, :pled conjugate.irregular :prove, :proved, :proved conjugate.irregular :put, :put, :put conjugate.irregular :quit, :quit, :quit conjugate.irregular :read, :read, :read conjugate.irregular :rid, :rid, :rid conjugate.irregular :ride, :rode, :ridden conjugate.irregular :ring, :rang, :rung conjugate.irregular :rise, :rose, :risen conjugate.irregular :run, :ran, :run conjugate.irregular :saw, :sawed, :sawed conjugate.irregular :say, :said, :said conjugate.irregular :see, :saw, :seen conjugate.irregular :seek, :sought, :sought conjugate.irregular :sell, :sold, :sold conjugate.irregular :send, :sent, :sent conjugate.irregular :set, :set, :set conjugate.irregular :sew, :sewed, :sewed conjugate.irregular :shake, :shook, :shaken conjugate.irregular :shave, :shaved, :shaved conjugate.irregular :shear, :shore, :shorn conjugate.irregular :shed, :shed, :shed conjugate.irregular :shine, :shone, :shone conjugate.irregular :shoe, :shoed, :shoed conjugate.irregular :shoot, :shot, :shot conjugate.irregular :show, :showed, :showed conjugate.irregular :shrink, :shrank, :shrunk conjugate.irregular :shut, :shut, :shut conjugate.irregular :sing, :sang, :sung conjugate.irregular :sink, :sank, :sunk conjugate.irregular :sit, :sat, :sat conjugate.irregular :sleep, :slept, :slept conjugate.irregular :slay, :slew, :slain conjugate.irregular :slide, :slid, :slid conjugate.irregular :sling, :slung, :slung conjugate.irregular :slit, :slit, :slit conjugate.irregular :smite, :smote, :smitten conjugate.irregular :sow, :sowed, :sowed conjugate.irregular :speak, :spoke, :spoken conjugate.irregular :speed, :sped, :sped conjugate.irregular :spend, :spent, :spent conjugate.irregular :spill, :spilled, :spilled conjugate.irregular :spin, :spun, :spun conjugate.irregular :spit, :spit, :spit conjugate.irregular :split, :split, :split conjugate.irregular :spread, :spread, :spread conjugate.irregular :spring, :sprang, :sprung conjugate.irregular :stand, :stood, :stood conjugate.irregular :steal, :stole, :stolen conjugate.irregular :stick, :stuck, :stuck conjugate.irregular :sting, :stung, :stung conjugate.irregular :stink, :stank, :stunk conjugate.irregular :stride, :strod, :stridden conjugate.irregular :strike, :struck, :struck conjugate.irregular :string, :strung, :strung conjugate.irregular :strive, :strove, :striven conjugate.irregular :swear, :swore, :sworn conjugate.irregular :sweep, :swept, :swept conjugate.irregular :swell, :swelled, :swelled conjugate.irregular :swim, :swam, :swum conjugate.irregular :swing, :swung, :swung conjugate.irregular :take, :took, :taken conjugate.irregular :teach, :taught, :taught conjugate.irregular :tear, :tore, :torn conjugate.irregular :tell, :told, :told conjugate.irregular :think, :thought, :thought conjugate.irregular :thrive, :thrived, :thrived conjugate.irregular :throw, :threw, :thrown conjugate.irregular :thrust, :thrust, :thrust conjugate.irregular :tread, :trod, :trodden conjugate.irregular :understand, :understood, :understood conjugate.irregular :uphold, :upheld, :upheld conjugate.irregular :upset, :upset, :upset conjugate.irregular :wake, :woke, :woken conjugate.irregular :wear, :wore, :worn conjugate.irregular :weave, :weaved, :weaved conjugate.irregular :wed, :wed, :wed conjugate.irregular :weep, :wept, :wept conjugate.irregular :wind, :wound, :wound conjugate.irregular :win, :won, :won conjugate.irregular :withhold, :withheld, :withheld conjugate.irregular :withstand, :withstood, :withstood conjugate.irregular :wring, :wrung, :wrung conjugate.irregular :write, :wrote, :written conjugate.single_terminal_consonant :abandon conjugate.single_terminal_consonant :accouter conjugate.single_terminal_consonant :accredit conjugate.single_terminal_consonant :adhibit conjugate.single_terminal_consonant :administer conjugate.single_terminal_consonant :alter conjugate.single_terminal_consonant :anchor conjugate.single_terminal_consonant :answer conjugate.single_terminal_consonant :attrit conjugate.single_terminal_consonant :audit conjugate.single_terminal_consonant :author conjugate.single_terminal_consonant :ballot conjugate.single_terminal_consonant :banner conjugate.single_terminal_consonant :batten conjugate.single_terminal_consonant :bedizen conjugate.single_terminal_consonant :bespatter conjugate.single_terminal_consonant :betoken conjugate.single_terminal_consonant :bewilder conjugate.single_terminal_consonant :billet conjugate.single_terminal_consonant :blacken conjugate.single_terminal_consonant :blither conjugate.single_terminal_consonant :blossom conjugate.single_terminal_consonant :bother conjugate.single_terminal_consonant :brighten conjugate.single_terminal_consonant :broaden conjugate.single_terminal_consonant :broider conjugate.single_terminal_consonant :burden conjugate.single_terminal_consonant :caparison conjugate.single_terminal_consonant :catalog conjugate.single_terminal_consonant :censor conjugate.single_terminal_consonant :center conjugate.single_terminal_consonant :charter conjugate.single_terminal_consonant :chatter conjugate.single_terminal_consonant :cheapen conjugate.single_terminal_consonant :chipper conjugate.single_terminal_consonant :chirrup conjugate.single_terminal_consonant :christen conjugate.single_terminal_consonant :clobber conjugate.single_terminal_consonant :cluster conjugate.single_terminal_consonant :coarsen conjugate.single_terminal_consonant :cocker conjugate.single_terminal_consonant :coedit conjugate.single_terminal_consonant :cohabit conjugate.single_terminal_consonant :concenter conjugate.single_terminal_consonant :corner conjugate.single_terminal_consonant :cover conjugate.single_terminal_consonant :covet conjugate.single_terminal_consonant :cower conjugate.single_terminal_consonant :credit conjugate.single_terminal_consonant :custom conjugate.single_terminal_consonant :dampen conjugate.single_terminal_consonant :deafen conjugate.single_terminal_consonant :decipher conjugate.single_terminal_consonant :deflower conjugate.single_terminal_consonant :delimit conjugate.single_terminal_consonant :deposit conjugate.single_terminal_consonant :develop conjugate.single_terminal_consonant :differ conjugate.single_terminal_consonant :disaccustom conjugate.single_terminal_consonant :discover conjugate.single_terminal_consonant :discredit conjugate.single_terminal_consonant :disencumber conjugate.single_terminal_consonant :dishearten conjugate.single_terminal_consonant :disinherit conjugate.single_terminal_consonant :dismember conjugate.single_terminal_consonant :dispirit conjugate.single_terminal_consonant :dither conjugate.single_terminal_consonant :dizen conjugate.single_terminal_consonant :dodder conjugate.single_terminal_consonant :edit conjugate.single_terminal_consonant :elicit conjugate.single_terminal_consonant :embitter conjugate.single_terminal_consonant :embolden conjugate.single_terminal_consonant :embosom conjugate.single_terminal_consonant :embower conjugate.single_terminal_consonant :empoison conjugate.single_terminal_consonant :empower conjugate.single_terminal_consonant :enamor conjugate.single_terminal_consonant :encipher conjugate.single_terminal_consonant :encounter conjugate.single_terminal_consonant :endanger conjugate.single_terminal_consonant :enfetter conjugate.single_terminal_consonant :engender conjugate.single_terminal_consonant :enlighten conjugate.single_terminal_consonant :enter conjugate.single_terminal_consonant :envelop conjugate.single_terminal_consonant :envenom conjugate.single_terminal_consonant :environ conjugate.single_terminal_consonant :exhibit conjugate.single_terminal_consonant :exit conjugate.single_terminal_consonant :fasten conjugate.single_terminal_consonant :fatten conjugate.single_terminal_consonant :feather conjugate.single_terminal_consonant :fester conjugate.single_terminal_consonant :filter conjugate.single_terminal_consonant :flatten conjugate.single_terminal_consonant :flatter conjugate.single_terminal_consonant :flounder conjugate.single_terminal_consonant :fluster conjugate.single_terminal_consonant :flutter conjugate.single_terminal_consonant :foreshorten conjugate.single_terminal_consonant :founder conjugate.single_terminal_consonant :fritter conjugate.single_terminal_consonant :gammon conjugate.single_terminal_consonant :gather conjugate.single_terminal_consonant :gladden conjugate.single_terminal_consonant :glimmer conjugate.single_terminal_consonant :glisten conjugate.single_terminal_consonant :glower conjugate.single_terminal_consonant :greaten conjugate.single_terminal_consonant :hamper conjugate.single_terminal_consonant :hanker conjugate.single_terminal_consonant :happen conjugate.single_terminal_consonant :harden conjugate.single_terminal_consonant :harken conjugate.single_terminal_consonant :hasten conjugate.single_terminal_consonant :hearten conjugate.single_terminal_consonant :hoarsen conjugate.single_terminal_consonant :honor conjugate.single_terminal_consonant :imprison conjugate.single_terminal_consonant :inhabit conjugate.single_terminal_consonant :inhibit conjugate.single_terminal_consonant :inspirit conjugate.single_terminal_consonant :interpret conjugate.single_terminal_consonant :iron conjugate.single_terminal_consonant :know conjugate.single_terminal_consonant :laten conjugate.single_terminal_consonant :launder conjugate.single_terminal_consonant :lengthen conjugate.single_terminal_consonant :liken conjugate.single_terminal_consonant :limber conjugate.single_terminal_consonant :limit conjugate.single_terminal_consonant :linger conjugate.single_terminal_consonant :litter conjugate.single_terminal_consonant :liven conjugate.single_terminal_consonant :loiter conjugate.single_terminal_consonant :lollop conjugate.single_terminal_consonant :louden conjugate.single_terminal_consonant :lower conjugate.single_terminal_consonant :lumber conjugate.single_terminal_consonant :madden conjugate.single_terminal_consonant :malinger conjugate.single_terminal_consonant :market conjugate.single_terminal_consonant :matter conjugate.single_terminal_consonant :misinterpret conjugate.single_terminal_consonant :misremember conjugate.single_terminal_consonant :monitor conjugate.single_terminal_consonant :moulder conjugate.single_terminal_consonant :murder conjugate.single_terminal_consonant :murmur conjugate.single_terminal_consonant :muster conjugate.single_terminal_consonant :number conjugate.single_terminal_consonant :offer conjugate.single_terminal_consonant :open conjugate.single_terminal_consonant :order conjugate.single_terminal_consonant :outmaneuver conjugate.single_terminal_consonant :overmaster conjugate.single_terminal_consonant :pamper conjugate.single_terminal_consonant :pilot conjugate.single_terminal_consonant :pivot conjugate.single_terminal_consonant :plaster conjugate.single_terminal_consonant :plunder conjugate.single_terminal_consonant :powder conjugate.single_terminal_consonant :power conjugate.single_terminal_consonant :prohibit conjugate.single_terminal_consonant :reckon conjugate.single_terminal_consonant :reconsider conjugate.single_terminal_consonant :recover conjugate.single_terminal_consonant :redden conjugate.single_terminal_consonant :redeliver conjugate.single_terminal_consonant :register conjugate.single_terminal_consonant :rejigger conjugate.single_terminal_consonant :remember conjugate.single_terminal_consonant :renumber conjugate.single_terminal_consonant :reopen conjugate.single_terminal_consonant :reposit conjugate.single_terminal_consonant :rewaken conjugate.single_terminal_consonant :richen conjugate.single_terminal_consonant :roister conjugate.single_terminal_consonant :roughen conjugate.single_terminal_consonant :sadden conjugate.single_terminal_consonant :savor conjugate.single_terminal_consonant :scatter conjugate.single_terminal_consonant :scupper conjugate.single_terminal_consonant :sharpen conjugate.single_terminal_consonant :shatter conjugate.single_terminal_consonant :shelter conjugate.single_terminal_consonant :shimmer conjugate.single_terminal_consonant :shiver conjugate.single_terminal_consonant :shorten conjugate.single_terminal_consonant :shower conjugate.single_terminal_consonant :sicken conjugate.single_terminal_consonant :smolder conjugate.single_terminal_consonant :smoothen conjugate.single_terminal_consonant :soften conjugate.single_terminal_consonant :solicit conjugate.single_terminal_consonant :squander conjugate.single_terminal_consonant :stagger conjugate.single_terminal_consonant :stiffen conjugate.single_terminal_consonant :stopper conjugate.single_terminal_consonant :stouten conjugate.single_terminal_consonant :straiten conjugate.single_terminal_consonant :strengthen conjugate.single_terminal_consonant :stutter conjugate.single_terminal_consonant :suffer conjugate.single_terminal_consonant :sugar conjugate.single_terminal_consonant :summon conjugate.single_terminal_consonant :surrender conjugate.single_terminal_consonant :swelter conjugate.single_terminal_consonant :sypher conjugate.single_terminal_consonant :tamper conjugate.single_terminal_consonant :tauten conjugate.single_terminal_consonant :tender conjugate.single_terminal_consonant :thicken conjugate.single_terminal_consonant :threaten conjugate.single_terminal_consonant :thunder conjugate.single_terminal_consonant :totter conjugate.single_terminal_consonant :toughen conjugate.single_terminal_consonant :tower conjugate.single_terminal_consonant :transit conjugate.single_terminal_consonant :tucker conjugate.single_terminal_consonant :unburden conjugate.single_terminal_consonant :uncover conjugate.single_terminal_consonant :unfetter conjugate.single_terminal_consonant :unloosen conjugate.single_terminal_consonant :upholster conjugate.single_terminal_consonant :utter conjugate.single_terminal_consonant :visit conjugate.single_terminal_consonant :vomit conjugate.single_terminal_consonant :wander conjugate.single_terminal_consonant :water conjugate.single_terminal_consonant :weaken conjugate.single_terminal_consonant :whiten conjugate.single_terminal_consonant :winter conjugate.single_terminal_consonant :wonder conjugate.single_terminal_consonant :worsen end Add "reset" to the irregular conjugation list. Verbs::Conjugator.conjugations do |conjugate| conjugate.irregular :be do |verb| # copular verb.form :am, :tense => :present, :person => :first, :plurality => :singular verb.form :is, :tense => :present, :person => :third, :plurality => :singular verb.form :are, :tense => :present, :person => :second, :plurality => :singular verb.form :are, :tense => :present, :person => :first, :plurality => :plural verb.form :are, :tense => :present, :person => :third, :plurality => :plural verb.form :was, :tense => :past, :person => :first, :plurality => :singular verb.form :was, :tense => :past, :person => :third, :plurality => :singular verb.form :were, :tense => :past, :person => :second, :plurality => :singular verb.form :were, :tense => :past, :person => :first, :plurality => :plural verb.form :were, :tense => :past, :person => :third, :plurality => :plural verb.form :were, :tense => :past, :mood => :subjunctive verb.form :be, :tense => :present, :mood => :subjunctive verb.form :being, :tense => :present, :derivative => :participle verb.form :been, :tense => :past, :derivative => :participle end conjugate.irregular :have do |verb| verb.form :have, :tense => :present, :person => :first, :plurality => :singular verb.form :has, :tense => :present, :person => :third, :plurality => :singular verb.form :have, :tense => :present, :person => :second, :plurality => :singular verb.form :have, :tense => :present, :person => :first, :plurality => :plural verb.form :have, :tense => :present, :person => :third, :plurality => :plural verb.form :had, :tense => :past, :person => :first, :plurality => :singular verb.form :had, :tense => :past, :person => :third, :plurality => :singular verb.form :had, :tense => :past, :person => :second, :plurality => :singular verb.form :had, :tense => :past, :person => :first, :plurality => :plural verb.form :had, :tense => :past, :person => :third, :plurality => :plural verb.form :having, :tense => :present, :derivative => :participle verb.form :had, :tense => :past, :derivative => :participle end # http://cpansearch.perl.org/src/RWG/Lingua-EN-Conjugate-0.308/lib/Lingua/EN/Conjugate.pm conjugate.irregular :awake, :awoke, :awoken conjugate.irregular :bear, :bore, :born conjugate.irregular :beat, :beat, :beat conjugate.irregular :become, :became, :become conjugate.irregular :begin, :began, :begun conjugate.irregular :bend, :bent, :bent conjugate.irregular :beset, :beset, :beset conjugate.irregular :bet, :bet, :bet conjugate.irregular :bid, :bid, :bid conjugate.irregular :bind, :bound, :bound conjugate.irregular :bite, :bit, :bitten conjugate.irregular :bleed, :bled, :bled conjugate.irregular :blow, :blew, :blown conjugate.irregular :break, :broke, :broken conjugate.irregular :breed, :bred, :bred conjugate.irregular :bring, :brought, :brought conjugate.irregular :broadcast, :broadcast, :broadcast conjugate.irregular :build, :built, :built conjugate.irregular :burn, :burned, :burned conjugate.irregular :burst, :burst, :burst conjugate.irregular :buy, :bought, :bought conjugate.irregular :cast, :cast, :cast conjugate.irregular :catch, :caught, :caught conjugate.irregular :choose, :chose, :chosen conjugate.irregular :cling, :clung, :clung conjugate.irregular :come, :came, :come conjugate.irregular :cost, :cost, :cost conjugate.irregular :creep, :crept, :crept conjugate.irregular :cut, :cut, :cut conjugate.irregular :deal, :dealt, :dealt conjugate.irregular :dig, :dug, :dug conjugate.irregular :dive, :dove, :dived conjugate.irregular 'do', :did, :done conjugate.irregular :draw, :drew, :drawn conjugate.irregular :dream, :dreamed, :dreamed conjugate.irregular :drive, :drove, :driven conjugate.irregular :drink, :drank, :drunk conjugate.irregular :eat, :ate, :eaten conjugate.irregular :fall, :fell, :fallen conjugate.irregular :feed, :fed, :fed conjugate.irregular :feel, :felt, :felt conjugate.irregular :fight, :fought, :fought conjugate.irregular :find, :found, :found conjugate.irregular :fit, :fit, :fit conjugate.irregular :flee, :fled, :fled conjugate.irregular :fling, :flung, :flung conjugate.irregular :fly, :flew, :flown conjugate.irregular :forbid, :forbade, :forbidden conjugate.irregular :forget, :forgot, :forgotten conjugate.irregular :forego, :forewent, :foregone conjugate.irregular :forgo, :forwent, :forgone conjugate.irregular :forgive, :forgave, :forgiven conjugate.irregular :forsake, :forsook, :forsaken conjugate.irregular :freeze, :froze, :frozen conjugate.irregular :get, :got, :gotten conjugate.irregular :give, :gave, :given conjugate.irregular :go, :went, :gone conjugate.irregular :grind, :ground, :ground conjugate.irregular :grow, :grew, :grown conjugate.irregular :hang, :hung, :hung conjugate.irregular :hear, :heard, :heard conjugate.irregular :hide, :hid, :hidden conjugate.irregular :hit, :hit, :hit conjugate.irregular :hold, :held, :held conjugate.irregular :hurt, :hurt, :hurt conjugate.irregular :keep, :kept, :kept conjugate.irregular :kneel, :knelt, :knelt conjugate.irregular :knit, :knit, :knit conjugate.irregular :know, :knew, :known conjugate.irregular :lay, :laid, :laid conjugate.irregular :lead, :led, :led conjugate.irregular :leap, :leaped, :leaped conjugate.irregular :learn, :learned, :learned conjugate.irregular :leave, :left, :left conjugate.irregular :lend, :lent, :lent conjugate.irregular :let, :let, :let conjugate.irregular :lie, :lay, :lain conjugate.irregular :light, :lit, :lighted conjugate.irregular :lose, :lost, :lost conjugate.irregular :make, :made, :made conjugate.irregular :mean, :meant, :meant conjugate.irregular :meet, :met, :met conjugate.irregular :misspell, :misspelled, :misspelled conjugate.irregular :mistake, :mistook, :mistaken conjugate.irregular :mow, :mowed, :mowed conjugate.irregular :overcome, :overcame, :overcome conjugate.irregular :overdo, :overdid, :overdone conjugate.irregular :overtake, :overtook, :overtaken conjugate.irregular :overthrow, :overthrew, :overthrown conjugate.irregular :pay, :paid, :paid conjugate.irregular :plead, :pled, :pled conjugate.irregular :prove, :proved, :proved conjugate.irregular :put, :put, :put conjugate.irregular :quit, :quit, :quit conjugate.irregular :read, :read, :read conjugate.irregular :reset, :reset, :reset conjugate.irregular :rid, :rid, :rid conjugate.irregular :ride, :rode, :ridden conjugate.irregular :ring, :rang, :rung conjugate.irregular :rise, :rose, :risen conjugate.irregular :run, :ran, :run conjugate.irregular :saw, :sawed, :sawed conjugate.irregular :say, :said, :said conjugate.irregular :see, :saw, :seen conjugate.irregular :seek, :sought, :sought conjugate.irregular :sell, :sold, :sold conjugate.irregular :send, :sent, :sent conjugate.irregular :set, :set, :set conjugate.irregular :sew, :sewed, :sewed conjugate.irregular :shake, :shook, :shaken conjugate.irregular :shave, :shaved, :shaved conjugate.irregular :shear, :shore, :shorn conjugate.irregular :shed, :shed, :shed conjugate.irregular :shine, :shone, :shone conjugate.irregular :shoe, :shoed, :shoed conjugate.irregular :shoot, :shot, :shot conjugate.irregular :show, :showed, :showed conjugate.irregular :shrink, :shrank, :shrunk conjugate.irregular :shut, :shut, :shut conjugate.irregular :sing, :sang, :sung conjugate.irregular :sink, :sank, :sunk conjugate.irregular :sit, :sat, :sat conjugate.irregular :sleep, :slept, :slept conjugate.irregular :slay, :slew, :slain conjugate.irregular :slide, :slid, :slid conjugate.irregular :sling, :slung, :slung conjugate.irregular :slit, :slit, :slit conjugate.irregular :smite, :smote, :smitten conjugate.irregular :sow, :sowed, :sowed conjugate.irregular :speak, :spoke, :spoken conjugate.irregular :speed, :sped, :sped conjugate.irregular :spend, :spent, :spent conjugate.irregular :spill, :spilled, :spilled conjugate.irregular :spin, :spun, :spun conjugate.irregular :spit, :spit, :spit conjugate.irregular :split, :split, :split conjugate.irregular :spread, :spread, :spread conjugate.irregular :spring, :sprang, :sprung conjugate.irregular :stand, :stood, :stood conjugate.irregular :steal, :stole, :stolen conjugate.irregular :stick, :stuck, :stuck conjugate.irregular :sting, :stung, :stung conjugate.irregular :stink, :stank, :stunk conjugate.irregular :stride, :strod, :stridden conjugate.irregular :strike, :struck, :struck conjugate.irregular :string, :strung, :strung conjugate.irregular :strive, :strove, :striven conjugate.irregular :swear, :swore, :sworn conjugate.irregular :sweep, :swept, :swept conjugate.irregular :swell, :swelled, :swelled conjugate.irregular :swim, :swam, :swum conjugate.irregular :swing, :swung, :swung conjugate.irregular :take, :took, :taken conjugate.irregular :teach, :taught, :taught conjugate.irregular :tear, :tore, :torn conjugate.irregular :tell, :told, :told conjugate.irregular :think, :thought, :thought conjugate.irregular :thrive, :thrived, :thrived conjugate.irregular :throw, :threw, :thrown conjugate.irregular :thrust, :thrust, :thrust conjugate.irregular :tread, :trod, :trodden conjugate.irregular :understand, :understood, :understood conjugate.irregular :uphold, :upheld, :upheld conjugate.irregular :upset, :upset, :upset conjugate.irregular :wake, :woke, :woken conjugate.irregular :wear, :wore, :worn conjugate.irregular :weave, :weaved, :weaved conjugate.irregular :wed, :wed, :wed conjugate.irregular :weep, :wept, :wept conjugate.irregular :wind, :wound, :wound conjugate.irregular :win, :won, :won conjugate.irregular :withhold, :withheld, :withheld conjugate.irregular :withstand, :withstood, :withstood conjugate.irregular :wring, :wrung, :wrung conjugate.irregular :write, :wrote, :written conjugate.single_terminal_consonant :abandon conjugate.single_terminal_consonant :accouter conjugate.single_terminal_consonant :accredit conjugate.single_terminal_consonant :adhibit conjugate.single_terminal_consonant :administer conjugate.single_terminal_consonant :alter conjugate.single_terminal_consonant :anchor conjugate.single_terminal_consonant :answer conjugate.single_terminal_consonant :attrit conjugate.single_terminal_consonant :audit conjugate.single_terminal_consonant :author conjugate.single_terminal_consonant :ballot conjugate.single_terminal_consonant :banner conjugate.single_terminal_consonant :batten conjugate.single_terminal_consonant :bedizen conjugate.single_terminal_consonant :bespatter conjugate.single_terminal_consonant :betoken conjugate.single_terminal_consonant :bewilder conjugate.single_terminal_consonant :billet conjugate.single_terminal_consonant :blacken conjugate.single_terminal_consonant :blither conjugate.single_terminal_consonant :blossom conjugate.single_terminal_consonant :bother conjugate.single_terminal_consonant :brighten conjugate.single_terminal_consonant :broaden conjugate.single_terminal_consonant :broider conjugate.single_terminal_consonant :burden conjugate.single_terminal_consonant :caparison conjugate.single_terminal_consonant :catalog conjugate.single_terminal_consonant :censor conjugate.single_terminal_consonant :center conjugate.single_terminal_consonant :charter conjugate.single_terminal_consonant :chatter conjugate.single_terminal_consonant :cheapen conjugate.single_terminal_consonant :chipper conjugate.single_terminal_consonant :chirrup conjugate.single_terminal_consonant :christen conjugate.single_terminal_consonant :clobber conjugate.single_terminal_consonant :cluster conjugate.single_terminal_consonant :coarsen conjugate.single_terminal_consonant :cocker conjugate.single_terminal_consonant :coedit conjugate.single_terminal_consonant :cohabit conjugate.single_terminal_consonant :concenter conjugate.single_terminal_consonant :corner conjugate.single_terminal_consonant :cover conjugate.single_terminal_consonant :covet conjugate.single_terminal_consonant :cower conjugate.single_terminal_consonant :credit conjugate.single_terminal_consonant :custom conjugate.single_terminal_consonant :dampen conjugate.single_terminal_consonant :deafen conjugate.single_terminal_consonant :decipher conjugate.single_terminal_consonant :deflower conjugate.single_terminal_consonant :delimit conjugate.single_terminal_consonant :deposit conjugate.single_terminal_consonant :develop conjugate.single_terminal_consonant :differ conjugate.single_terminal_consonant :disaccustom conjugate.single_terminal_consonant :discover conjugate.single_terminal_consonant :discredit conjugate.single_terminal_consonant :disencumber conjugate.single_terminal_consonant :dishearten conjugate.single_terminal_consonant :disinherit conjugate.single_terminal_consonant :dismember conjugate.single_terminal_consonant :dispirit conjugate.single_terminal_consonant :dither conjugate.single_terminal_consonant :dizen conjugate.single_terminal_consonant :dodder conjugate.single_terminal_consonant :edit conjugate.single_terminal_consonant :elicit conjugate.single_terminal_consonant :embitter conjugate.single_terminal_consonant :embolden conjugate.single_terminal_consonant :embosom conjugate.single_terminal_consonant :embower conjugate.single_terminal_consonant :empoison conjugate.single_terminal_consonant :empower conjugate.single_terminal_consonant :enamor conjugate.single_terminal_consonant :encipher conjugate.single_terminal_consonant :encounter conjugate.single_terminal_consonant :endanger conjugate.single_terminal_consonant :enfetter conjugate.single_terminal_consonant :engender conjugate.single_terminal_consonant :enlighten conjugate.single_terminal_consonant :enter conjugate.single_terminal_consonant :envelop conjugate.single_terminal_consonant :envenom conjugate.single_terminal_consonant :environ conjugate.single_terminal_consonant :exhibit conjugate.single_terminal_consonant :exit conjugate.single_terminal_consonant :fasten conjugate.single_terminal_consonant :fatten conjugate.single_terminal_consonant :feather conjugate.single_terminal_consonant :fester conjugate.single_terminal_consonant :filter conjugate.single_terminal_consonant :flatten conjugate.single_terminal_consonant :flatter conjugate.single_terminal_consonant :flounder conjugate.single_terminal_consonant :fluster conjugate.single_terminal_consonant :flutter conjugate.single_terminal_consonant :foreshorten conjugate.single_terminal_consonant :founder conjugate.single_terminal_consonant :fritter conjugate.single_terminal_consonant :gammon conjugate.single_terminal_consonant :gather conjugate.single_terminal_consonant :gladden conjugate.single_terminal_consonant :glimmer conjugate.single_terminal_consonant :glisten conjugate.single_terminal_consonant :glower conjugate.single_terminal_consonant :greaten conjugate.single_terminal_consonant :hamper conjugate.single_terminal_consonant :hanker conjugate.single_terminal_consonant :happen conjugate.single_terminal_consonant :harden conjugate.single_terminal_consonant :harken conjugate.single_terminal_consonant :hasten conjugate.single_terminal_consonant :hearten conjugate.single_terminal_consonant :hoarsen conjugate.single_terminal_consonant :honor conjugate.single_terminal_consonant :imprison conjugate.single_terminal_consonant :inhabit conjugate.single_terminal_consonant :inhibit conjugate.single_terminal_consonant :inspirit conjugate.single_terminal_consonant :interpret conjugate.single_terminal_consonant :iron conjugate.single_terminal_consonant :know conjugate.single_terminal_consonant :laten conjugate.single_terminal_consonant :launder conjugate.single_terminal_consonant :lengthen conjugate.single_terminal_consonant :liken conjugate.single_terminal_consonant :limber conjugate.single_terminal_consonant :limit conjugate.single_terminal_consonant :linger conjugate.single_terminal_consonant :litter conjugate.single_terminal_consonant :liven conjugate.single_terminal_consonant :loiter conjugate.single_terminal_consonant :lollop conjugate.single_terminal_consonant :louden conjugate.single_terminal_consonant :lower conjugate.single_terminal_consonant :lumber conjugate.single_terminal_consonant :madden conjugate.single_terminal_consonant :malinger conjugate.single_terminal_consonant :market conjugate.single_terminal_consonant :matter conjugate.single_terminal_consonant :misinterpret conjugate.single_terminal_consonant :misremember conjugate.single_terminal_consonant :monitor conjugate.single_terminal_consonant :moulder conjugate.single_terminal_consonant :murder conjugate.single_terminal_consonant :murmur conjugate.single_terminal_consonant :muster conjugate.single_terminal_consonant :number conjugate.single_terminal_consonant :offer conjugate.single_terminal_consonant :open conjugate.single_terminal_consonant :order conjugate.single_terminal_consonant :outmaneuver conjugate.single_terminal_consonant :overmaster conjugate.single_terminal_consonant :pamper conjugate.single_terminal_consonant :pilot conjugate.single_terminal_consonant :pivot conjugate.single_terminal_consonant :plaster conjugate.single_terminal_consonant :plunder conjugate.single_terminal_consonant :powder conjugate.single_terminal_consonant :power conjugate.single_terminal_consonant :prohibit conjugate.single_terminal_consonant :reckon conjugate.single_terminal_consonant :reconsider conjugate.single_terminal_consonant :recover conjugate.single_terminal_consonant :redden conjugate.single_terminal_consonant :redeliver conjugate.single_terminal_consonant :register conjugate.single_terminal_consonant :rejigger conjugate.single_terminal_consonant :remember conjugate.single_terminal_consonant :renumber conjugate.single_terminal_consonant :reopen conjugate.single_terminal_consonant :reposit conjugate.single_terminal_consonant :rewaken conjugate.single_terminal_consonant :richen conjugate.single_terminal_consonant :roister conjugate.single_terminal_consonant :roughen conjugate.single_terminal_consonant :sadden conjugate.single_terminal_consonant :savor conjugate.single_terminal_consonant :scatter conjugate.single_terminal_consonant :scupper conjugate.single_terminal_consonant :sharpen conjugate.single_terminal_consonant :shatter conjugate.single_terminal_consonant :shelter conjugate.single_terminal_consonant :shimmer conjugate.single_terminal_consonant :shiver conjugate.single_terminal_consonant :shorten conjugate.single_terminal_consonant :shower conjugate.single_terminal_consonant :sicken conjugate.single_terminal_consonant :smolder conjugate.single_terminal_consonant :smoothen conjugate.single_terminal_consonant :soften conjugate.single_terminal_consonant :solicit conjugate.single_terminal_consonant :squander conjugate.single_terminal_consonant :stagger conjugate.single_terminal_consonant :stiffen conjugate.single_terminal_consonant :stopper conjugate.single_terminal_consonant :stouten conjugate.single_terminal_consonant :straiten conjugate.single_terminal_consonant :strengthen conjugate.single_terminal_consonant :stutter conjugate.single_terminal_consonant :suffer conjugate.single_terminal_consonant :sugar conjugate.single_terminal_consonant :summon conjugate.single_terminal_consonant :surrender conjugate.single_terminal_consonant :swelter conjugate.single_terminal_consonant :sypher conjugate.single_terminal_consonant :tamper conjugate.single_terminal_consonant :tauten conjugate.single_terminal_consonant :tender conjugate.single_terminal_consonant :thicken conjugate.single_terminal_consonant :threaten conjugate.single_terminal_consonant :thunder conjugate.single_terminal_consonant :totter conjugate.single_terminal_consonant :toughen conjugate.single_terminal_consonant :tower conjugate.single_terminal_consonant :transit conjugate.single_terminal_consonant :tucker conjugate.single_terminal_consonant :unburden conjugate.single_terminal_consonant :uncover conjugate.single_terminal_consonant :unfetter conjugate.single_terminal_consonant :unloosen conjugate.single_terminal_consonant :upholster conjugate.single_terminal_consonant :utter conjugate.single_terminal_consonant :visit conjugate.single_terminal_consonant :vomit conjugate.single_terminal_consonant :wander conjugate.single_terminal_consonant :water conjugate.single_terminal_consonant :weaken conjugate.single_terminal_consonant :whiten conjugate.single_terminal_consonant :winter conjugate.single_terminal_consonant :wonder conjugate.single_terminal_consonant :worsen end
require './lib/ffi-gdal' require 'pp' #dir = '../../agrian/gis_engine/test/test_files' #name = 'empty_red_image.tif' #name = 'empty_black_image.tif' #dir = '~/Desktop/geotiffs' #name = 'NDVI20000201032.tif' #name = 'NDVI20000701183.tif' #name = 'NDVI20000701183.zip' #name = 'NDVI20000401092.tif' #dir = './spec/support' #name = 'google_earth_test.jpg' #name = 'compassdata_gcparchive_google_earth.kmz' dir = './spec/support/aaron/Floyd' name = 'Floyd_1058_20140612_NRGB.tif' #dir = './spec/support/osgeo' #name = 'c41078a1.tif' #dir = './spec/support/ShapeDailyCurrent' #name = '851449507.dbf' #name = '851449507.prj' filename = File.expand_path(name, dir) dataset = GDAL::Dataset.new(filename, 'r') puts '#------------------------------------------------------------------------' puts '#' puts "# #{GDAL.long_version}" puts '#' puts '# Build info:' GDAL.build_info.each do |k, v| puts "# - #{k} -> #{v}" end puts '#' puts '#------------------------------------------------------------------------' puts '#------------------------------------------------------------------------' puts '# Dataset Info' puts '#------------------------------------------------------------------------' puts "* Description:\t\t\t#{dataset.description}" puts "* Raster size (x, y):\t\t#{dataset.raster_x_size}, #{dataset.raster_y_size}" puts "* Raster count:\t\t\t#{dataset.raster_count}" puts "* Access flag:\t\t\t#{dataset.access_flag}" puts "* Projection definition:\t#{dataset.projection_definition}" puts "File\t\t\t\t- #{dataset.file_path}" puts '* Metadata' dataset.all_metadata.each do |domain, data| puts "\t\t\t\t+ Domain: #{domain}" if data.empty? puts "\t\t\t\t\t- No values" else data.each do |k, v| print "\t\t\t\t\t- #{k} => " pp v end end end p dataset.file_list dataset.to_a #exit puts puts '#------------------------------------------------------------------------' puts '# Driver Info' puts '#------------------------------------------------------------------------' puts "* Description:\t\t#{dataset.driver.description}" puts "* Short name:\t\t#{dataset.driver.short_name}" puts "* Long name:\t\t#{dataset.driver.long_name}" puts "* Help topic:\t\t#{dataset.driver.help_topic}" puts '* Metadata:' dataset.driver.all_metadata.each do |domain, data| puts "\t\t\t\t+ Domain: #{domain}" if data.empty? puts "\t\t\t\t\t- No values" else data.each do |k, v| print "\t\t\t\t\t- #{k} => " pp v end end end puts '* Creation option list:' dataset.driver.creation_option_list.each do |option| puts "\t\t\t- #{option}" unless option.empty? end puts if dataset.raster_count > 0 puts '#------------------------------------------------------------------------' puts '# Raster Band Info' puts '#------------------------------------------------------------------------' (1..dataset.raster_count).each do |i| band = dataset.raster_band(i) puts "* Band #{i}/#{dataset.raster_count}" puts " + description:\t\t\t#{band.description}" puts " + size (x,y):\t\t\t#{band.x_size},#{band.y_size}" puts " + no-data value:\t\t#{band.no_data_value}" puts " + access flag:\t\t#{band.access_flag}" puts " + number:\t\t\t#{band.number}" puts " + color interp:\t\t#{band.color_interpretation}" puts " + type:\t\t\t#{band.data_type}" puts " + block size:\t\t\t#{band.block_size}" puts " + category names:\t\t#{band.category_names}" band.category_names = 'meow' puts " + category names:\t\t#{band.category_names}" puts " + value range:\t\t#{band.minimum_value}..#{band.maximum_value}" puts " + read:\t\t\t#{band.read}" puts " + unit type:\t\t\t#{band.unit_type}" puts " + statistics:\t\t\t#{band.statistics}" puts " + scale:\t\t\t#{band.scale}" puts " + offset:\t\t\t#{band.offset}" puts " + mask flags:\t\t\t#{band.mask_flags}" #puts " + default histogram:\t\t\t#{band.default_histogram}" #puts " + histogram:\t\t\t#{band.histogram(-0.5, 255.5, 256)}" if band.mask_band puts ' + Mask band:' puts " - number:\t\t\t\t#{band.mask_band.number}" puts " - size (x,y):\t\t\t#{band.mask_band.x_size},#{band.mask_band.y_size}" puts " - color interp:\t\t\t#{band.mask_band.color_interpretation}" puts " - type:\t\t\t\t#{band.mask_band.data_type}" puts " - block size:\t\t\t#{band.mask_band.block_size}" puts " - value range:\t\t\t#{band.mask_band.minimum_value}..#{band.mask_band.maximum_value}" end puts " + has arbitrary overviews?\t#{band.arbitrary_overviews?}" puts " + raster sample overview:\t#{band.raster_sample_overview}" puts " + overview count:\t\t#{band.overview_count}" if band.overview_count > 0 (0...band.overview_count).each do |j| overview = band.overview(j) puts " # Overview #{j} Info:" puts " - size (x, y):\t\t#{overview.x_size}, #{overview.y_size}" puts " - color interp:\t\t#{overview.color_interpretation}" puts " - type:\t\t\t#{overview.data_type}" puts " - block size:\t\t#{overview.block_size}" puts " - value range:\t\t#{overview.minimum_value}..#{overview.maximum_value}" puts " - overview count:\t\t#{overview.overview_count}" end end puts ' + Metadata:' band.all_metadata.each do |domain, data| puts "\t\t\t\t+ Domain: #{domain}" if data.empty? puts "\t\t\t\t\t- No values" else data.each do |k, v| print "\t\t\t\t\t- #{k} => " pp v end end end if band.color_table puts ' + Color Table Info' puts " - palette interp:\t\t#{band.color_table.palette_interpretation}" puts " - color entry count:\t#{band.color_table.color_entry_count}" if band.color_table.color_entry_count > 0 puts " - #{band.color_table.color_entry_count} color entries:" (0...band.color_table.color_entry_count).each do |j| ce = band.color_table.color_entry(j) ce_string = "(#{ce[:c1]},#{ce[:c2]},#{ce[:c3]},#{ce[:c4]})" rgb = band.color_table.color_entry_as_rgb(j) rgb_string = "(#{rgb[:c1]},#{rgb[:c2]},#{rgb[:c3]},#{rgb[:c4]})" if band.color_table.palette_interpretation == :GPI_RGB puts "\t\t\t\t~ #{j}:\t#{ce_string}" else puts "\t\t\t\t~ #{j}:\t#{ce_string}, RGB: #{rgb_string}" end end else puts ' - No Color Entry Info.' end end end end puts puts '#------------------------------------------------------------------------' puts '# Ground Control Point (GCP) Info' puts '#------------------------------------------------------------------------' puts "* GCP count:\t\t\t#{dataset.gcp_count}" if dataset.gcp_count > 0 puts "* GCP projection:\t\t'#{dataset.gcp_projection}'" puts '* GCPs:' puts " + ID:\t\t\t\t'#{dataset.gcps[:id]}'" puts " + Info:\t\t\t'#{dataset.gcps[:info]}'" puts " + Pixel:\t\t\t#{dataset.gcps[:pixel]}" puts " + Line:\t\t\t#{dataset.gcps[:line]}" puts " + X:\t\t\t\t#{dataset.gcps[:x]}" puts " + Y:\t\t\t\t#{dataset.gcps[:y]}" puts " + Z:\t\t\t\t#{dataset.gcps[:z]}" end puts puts '#------------------------------------------------------------------------' puts '# Geo-transform Info' puts '#------------------------------------------------------------------------' puts "* x origin (C):\t\t\t#{dataset.geo_transform.x_origin}" puts "* y origin (F):\t\t\t#{dataset.geo_transform.y_origin}" puts "* pixel width (A):\t\t#{dataset.geo_transform.pixel_width}" puts "* pixel height (E):\t\t#{dataset.geo_transform.pixel_height}" puts "* x rotation (B):\t\t#{dataset.geo_transform.x_rotation}" puts "* y rotation (D):\t\t#{dataset.geo_transform.y_rotation}" puts "* x projection (0.1, 0.2):\t#{dataset.geo_transform.x_projection(0.1, 0.2)}" puts "* y projection (0.2, 0.1):\t#{dataset.geo_transform.y_projection(0.2, 0.1)}" puts '#----------------------------------------------------' Nicer, relative pathnames for files require './lib/ffi-gdal' require 'pp' require 'pathname' #dir = '../../agrian/gis_engine/test/test_files' #name = 'empty_red_image.tif' #name = 'empty_black_image.tif' #dir = '~/Desktop/geotiffs' #name = 'NDVI20000201032.tif' #name = 'NDVI20000701183.tif' #name = 'NDVI20000701183.zip' #name = 'NDVI20000401092.tif' #dir = './spec/support' #name = 'google_earth_test.jpg' #name = 'compassdata_gcparchive_google_earth.kmz' #dir = './spec/support/aaron/Floyd' #name = 'Floyd_1058_20140612_NRGB.tif' dir = './spec/support/images/Harper' name = 'Harper_1058_20140612_NRGB.tif' #dir = './spec/support/osgeo' #name = 'c41078a1.tif' #dir = './spec/support/ShapeDailyCurrent' #name = '851449507.dbf' #name = '851449507.prj' filename = File.expand_path(name, dir) dataset = GDAL::Dataset.new(filename, 'r') current_directory = Pathname.new(Dir.pwd) puts '#------------------------------------------------------------------------' puts '#' puts "# #{GDAL.long_version}" puts '#' puts '# Build info:' GDAL.build_info.each do |k, v| puts "# - #{k} -> #{v}" end puts '#' puts '#------------------------------------------------------------------------' puts '#------------------------------------------------------------------------' puts '# Dataset Info' puts '#------------------------------------------------------------------------' puts "* Description:\t\t\t#{dataset.description}" puts "* Raster size (x, y):\t\t#{dataset.raster_x_size}, #{dataset.raster_y_size}" puts "* Raster count:\t\t\t#{dataset.raster_count}" puts "* Access flag:\t\t\t#{dataset.access_flag}" puts "* Projection definition:\t#{dataset.projection_definition}" puts "* Base File\t\t\t#{Pathname.new(dataset.file_path).relative_path_from(current_directory)}" puts '* File list:' dataset.file_list.each do |path| p = Pathname.new(path) puts "\t\t\t\t- #{p.relative_path_from(current_directory)}" end puts '* Metadata' dataset.all_metadata.each do |domain, data| puts "\t\t\t\t+ Domain: #{domain}" if data.empty? puts "\t\t\t\t\t- No values" else data.each do |k, v| print "\t\t\t\t\t- #{k} => " pp v end end end puts '#------------------------------------------------------------------------' puts '# Driver Info' puts '#------------------------------------------------------------------------' puts "* Description:\t\t#{dataset.driver.description}" puts "* Short name:\t\t#{dataset.driver.short_name}" puts "* Long name:\t\t#{dataset.driver.long_name}" puts "* Help topic:\t\t#{dataset.driver.help_topic}" puts '* Metadata:' dataset.driver.all_metadata.each do |domain, data| puts "\t\t\t+ Domain: #{domain}" if data.empty? puts "\t\t\t\t- No values" else data.each do |k, v| print "\t\t\t\t- #{k} => " pp v end end end puts '* Creation option list:' dataset.driver.creation_option_list.each do |option| puts "\t\t\t- #{option}" unless option.empty? end puts if dataset.raster_count > 0 puts '#------------------------------------------------------------------------' puts '# Raster Band Info' puts '#------------------------------------------------------------------------' (1..dataset.raster_count).each do |i| band = dataset.raster_band(i) puts "* Band #{i}/#{dataset.raster_count}" puts " - description:\t\t\t#{band.description}" puts " - size (x,y):\t\t\t#{band.x_size},#{band.y_size}" puts " - no-data value:\t\t#{band.no_data_value}" puts " - access flag:\t\t#{band.access_flag}" puts " - number:\t\t\t#{band.number}" puts " - color interp:\t\t#{band.color_interpretation}" puts " - type:\t\t\t#{band.data_type}" puts " - block size:\t\t\t#{band.block_size}" puts " - category names:\t\t#{band.category_names}" band.category_names = 'meow' puts " - category names:\t\t#{band.category_names}" puts " - value range:\t\t#{band.minimum_value}..#{band.maximum_value}" #puts " + read:\t\t\t#{band.read}" puts " - unit type:\t\t\t#{band.unit_type}" puts " - statistics:\t\t\t#{band.statistics}" puts " - scale:\t\t\t#{band.scale}" puts " - offset:\t\t\t#{band.offset}" puts " - mask flags:\t\t\t#{band.mask_flags}" #puts " + default histogram:\t\t\t#{band.default_histogram}" #puts " + histogram:\t\t\t#{band.histogram(-0.5, 255.5, 256)}" if band.mask_band puts ' + Mask band:' puts " - number:\t\t\t\t#{band.mask_band.number}" puts " - size (x,y):\t\t\t#{band.mask_band.x_size},#{band.mask_band.y_size}" puts " - color interp:\t\t\t#{band.mask_band.color_interpretation}" puts " - type:\t\t\t\t#{band.mask_band.data_type}" puts " - block size:\t\t\t#{band.mask_band.block_size}" puts " - value range:\t\t\t#{band.mask_band.minimum_value}..#{band.mask_band.maximum_value}" end puts " - has arbitrary overviews?\t#{band.arbitrary_overviews?}" puts " - raster sample overview:\t#{band.raster_sample_overview}" puts " - overview count:\t\t#{band.overview_count}" if band.overview_count > 0 (0...band.overview_count).each do |j| overview = band.overview(j) puts " # Overview #{j} Info:" puts " - size (x, y):\t\t#{overview.x_size}, #{overview.y_size}" puts " - color interp:\t\t#{overview.color_interpretation}" puts " - type:\t\t\t#{overview.data_type}" puts " - block size:\t\t#{overview.block_size}" puts " - value range:\t\t#{overview.minimum_value}..#{overview.maximum_value}" puts " - overview count:\t\t#{overview.overview_count}" end end puts ' + Metadata:' band.all_metadata.each do |domain, data| puts "\t\t\t\t+ Domain: #{domain}" if data.empty? puts "\t\t\t\t\t- No values" else data.each do |k, v| print "\t\t\t\t\t- #{k} => " pp v end end end if band.color_table puts ' + Color Table Info' puts " - palette interp:\t\t#{band.color_table.palette_interpretation}" puts " - color entry count:\t#{band.color_table.color_entry_count}" if band.color_table.color_entry_count > 0 puts " - #{band.color_table.color_entry_count} color entries:" (0...band.color_table.color_entry_count).each do |j| ce = band.color_table.color_entry(j) ce_string = "(#{ce[:c1]},#{ce[:c2]},#{ce[:c3]},#{ce[:c4]})" rgb = band.color_table.color_entry_as_rgb(j) rgb_string = "(#{rgb[:c1]},#{rgb[:c2]},#{rgb[:c3]},#{rgb[:c4]})" if band.color_table.palette_interpretation == :GPI_RGB puts "\t\t\t\t~ #{j}:\t#{ce_string}" else puts "\t\t\t\t~ #{j}:\t#{ce_string}, RGB: #{rgb_string}" end end else puts ' - No Color Entry Info.' end end end end puts puts '#------------------------------------------------------------------------' puts '# Ground Control Point (GCP) Info' puts '#------------------------------------------------------------------------' puts "* GCP count:\t\t\t#{dataset.gcp_count}" if dataset.gcp_count > 0 puts "* GCP projection:\t\t'#{dataset.gcp_projection}'" puts '* GCPs:' puts "\t\t\t- ID:\t\t\t\t'#{dataset.gcps[:id]}'" puts "\t\t\t- Info:\t\t\t'#{dataset.gcps[:info]}'" puts "\t\t\t- Pixel:\t\t\t#{dataset.gcps[:pixel]}" puts "\t\t\t- Line:\t\t\t#{dataset.gcps[:line]}" puts "\t\t\t- X:\t\t\t\t#{dataset.gcps[:x]}" puts "\t\t\t- Y:\t\t\t\t#{dataset.gcps[:y]}" puts "\t\t\t- Z:\t\t\t\t#{dataset.gcps[:z]}" end puts puts '#------------------------------------------------------------------------' puts '# Geo-transform Info' puts '#------------------------------------------------------------------------' puts "* x origin (C):\t\t\t#{dataset.geo_transform.x_origin}" puts "* y origin (F):\t\t\t#{dataset.geo_transform.y_origin}" puts "* pixel width (A):\t\t#{dataset.geo_transform.pixel_width}" puts "* pixel height (E):\t\t#{dataset.geo_transform.pixel_height}" puts "* x rotation (B):\t\t#{dataset.geo_transform.x_rotation}" puts "* y rotation (D):\t\t#{dataset.geo_transform.y_rotation}" puts "* x projection (0.1, 0.2):\t#{dataset.geo_transform.x_projection(0.1, 0.2)}" puts "* y projection (0.2, 0.1):\t#{dataset.geo_transform.y_projection(0.2, 0.1)}" puts '#----------------------------------------------------'
module Versioneye VERSION = '9.5.21' end Bump version module Versioneye VERSION = '9.5.22' end
require 'bencode' class VideoTorrentInfo autoload :TorrentClient, 'torrent_client' autoload :FFmpegVideoInfo, 'ffmpeg_video_info' DEFAULTS = { port1: 8661, port2: 8662, temp_path: '/tmp', supported_extensions: %w{ .avi .mkv .mpg .mpeg .3gp .wmv .mov .flv .mts }, download_limit: -1, timeout: 60 } def initialize(params = {}) @params = DEFAULTS.merge(params) @torrent_client = VideoTorrentInfo::TorrentClient.new end def load(torrent_path) dest = download_video(torrent_path) res = FFmpegVideoInfo.get(dest) File.unlink(dest) res end def download_video(torrent_path) string = File.open(torrent_path){ |file| file.read } torrent = string.bdecode files = get_video_files(torrent) @torrent_client.load(torrent_path, files.keys.first, @params[:download_limit], @params[:temp_path], @params[:port1], @params[:port2], @params[:timeout]) @params[:temp_path] + '/' + files.values.first end def get_video_files(torrent) info = torrent['info'] res = {} files = [] if info['files'].nil? files = [info['name']] else files = info['files'].map { |e| ([info['name']] + e['path']).join('/') } end files.each do |f| if @params[:supported_extensions].include?(File.extname(f)) res[files.index(f)] = f end end res end end add mp4 require 'bencode' class VideoTorrentInfo autoload :TorrentClient, 'torrent_client' autoload :FFmpegVideoInfo, 'ffmpeg_video_info' DEFAULTS = { port1: 8661, port2: 8662, temp_path: '/tmp', supported_extensions: %w{ .avi .mkv .mpg .mpeg .3gp .wmv .mov .flv .mts .mp4 }, download_limit: -1, timeout: 60 } def initialize(params = {}) @params = DEFAULTS.merge(params) @torrent_client = VideoTorrentInfo::TorrentClient.new end def load(torrent_path) dest = download_video(torrent_path) res = FFmpegVideoInfo.get(dest) File.unlink(dest) res end def download_video(torrent_path) string = File.open(torrent_path){ |file| file.read } torrent = string.bdecode files = get_video_files(torrent) @torrent_client.load(torrent_path, files.keys.first, @params[:download_limit], @params[:temp_path], @params[:port1], @params[:port2], @params[:timeout]) @params[:temp_path] + '/' + files.values.first end def get_video_files(torrent) info = torrent['info'] res = {} files = [] if info['files'].nil? files = [info['name']] else files = info['files'].map { |e| ([info['name']] + e['path']).join('/') } end files.each do |f| if @params[:supported_extensions].include?(File.extname(f)) res[files.index(f)] = f end end raise "No files supported" if res.empty? res end end
#!/usr/bin/env ruby require_relative 'Grammar' # # Preprocess the emerald code and add notion of indentation so it may be parsed # by a context free grammar. Removes all whitespace and adds braces to denote # indentation. # module PreProcessor # Instance variables @in_literal = false @current_indent = 0 @new_indent = 0 @b_count = 0 @output = '' def self.process_emerald(file_name) input = File.open(file_name, 'r').read input.each_line do |line| next if line.lstrip.empty? new_indent = line.length - line.lstrip.length check_new_indent(new_indent) parse_literal_whitespace(line) check_if_suffix_arrow(line) end print_remaining_braces @output end # Compares the value of the new_indent with the old indentation. # Invoked by: process_emerald def self.check_new_indent(new_indent) if new_indent > @current_indent new_indent_greater(new_indent) elsif new_indent < @current_indent && new_indent.nonzero? new_indent_lesser(new_indent) end end # Invoked by: check_new_indent def self.new_indent_greater(new_indent) unless @in_literal @output += "{\n" @b_count += 1 @current_indent = new_indent end end # Invoked by: check_new_indent def self.new_indent_lesser(new_indent) if @in_literal append_closing_braces(new_indent) else append_opening_braces(new_indent) end @current_indent = new_indent end def self.append_closing_braces(new_indent) @output += "$\n" @in_literal = false for i in 2..((@current_indent - new_indent) / 2) do @output += "}\n" @b_count -= 1 end end def self.append_opening_braces(new_indent) for i in 1..((@current_indent - new_indent) / 2) do @output += "}\n" @b_count -= 1 end end def self.parse_literal_whitespace(line) if @in_literal # Crop off only Emerald indent whitespace to preserve # whitespace in the literal @output += (line[@current_indent..-1] || '').gsub('$', '\$') # $ is our end character, so we need to escape it in # the literal else @output += line.lstrip end end def self.check_if_suffix_arrow(line) if line.rstrip.end_with?('->') @in_literal = true @current_indent += 2 end end def self.print_remaining_braces for i in 1..@b_count do @output += "}\n" end end end Updated PrePocessor.rb to be more rubocop compliant. #!/usr/bin/env ruby require_relative 'Grammar' # # Preprocess the emerald code and add notion of indentation so it may be parsed # by a context free grammar. Removes all whitespace and adds braces to denote # indentation. # module PreProcessor @in_literal = false @current_indent = 0 @new_indent = 0 @b_count = 0 @output = '' def self.process_emerald(file_name) input = File.open(file_name, 'r').read input.each_line do |line| next if line.lstrip.empty? new_indent = line.length - line.lstrip.length check_new_indent(new_indent) parse_literal_whitespace(line) check_if_suffix_arrow(line) end print_remaining_braces @output end # Compares the value of the new_indent with the old indentation. # Invoked by: process_emerald def self.check_new_indent(new_indent) if new_indent > @current_indent new_indent_greater(new_indent) elsif new_indent < @current_indent && new_indent.nonzero? new_indent_lesser(new_indent) end end # Invoked by: check_new_indent def self.new_indent_greater(new_indent) unless @in_literal @output += "{\n" @b_count += 1 @current_indent = new_indent end end # Invoked by: check_new_indent def self.new_indent_lesser(new_indent) if @in_literal append_closing_braces(new_indent) else append_opening_braces(new_indent) end @current_indent = new_indent end def self.append_closing_braces(new_indent) @output += "$\n" @in_literal = false (2..((@current_indent - new_indent) / 2)).each do @output += "}\n" @b_count -= 1 end end def self.append_opening_braces(new_indent) (1..((@current_indent - new_indent) / 2)).each do @output += "}\n" @b_count -= 1 end end def self.parse_literal_whitespace(line) # Crop off only Emerald indent whitespace to preserve # whitespace in the literal. # $ is our end character, so we need to escape it in # the literal. @output += if @in_literal (line[@current_indent..-1] || '').gsub('$', '\$') else line.lstrip end end def self.check_if_suffix_arrow(line) if line.rstrip.end_with?('->') @in_literal = true @current_indent += 2 end end def self.print_remaining_braces (1..@b_count).each do @output += "}\n" end end end
#Etsy Foodcritic rules @coreservices = ["httpd", "mysql", "memcached", "postgresql-server"] @coreservicepackages = ["httpd", "Percona-Server-server-51", "memcached", "postgresql-server"] @corecommands = ["yum -y", "yum install", "yum reinstall", "yum remove", "mkdir", "useradd", "usermod", "touch"] rule "ETSY001", "Package or yum_package resource used with :upgrade action" do tags %w{correctness recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end pres.concat(ypres).map{|cmd| match(cmd)} end end rule "ETSY002", "Execute resource used to run git commands" do tags %w{style recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s cmd_str.include?('git ') end.map{|cmd| match(cmd)} end end rule "ETSY003", "Execute resource used to run curl or wget commands" do tags %w{style recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s (cmd_str.include?('curl ') || cmd_str.include?('wget ')) end.map{|cmd| match(cmd)} end end # This rule does not detect execute resources defined inside a conditional, as foodcritic rule FC023 (Prefer conditional attributes) # already provides this. It's recommended to use both rules in conjunction. (foodcritic -t etsy,FC023) rule "ETSY004", "Execute resource defined without conditional or action :nothing" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_actions = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s condition = cmd.xpath('//ident[@value="only_if" or @value="not_if" or @value="creates"][parent::fcall or parent::command or ancestor::if]') (condition.empty? && !cmd_actions.include?("nothing")) end.map{|cmd| match(cmd)} end end rule "ETSY005", "Action :restart sent to a core service" do tags %w{correctness recipe etsy} recipe do |ast, filename| ast.xpath('//command[ident/@value = "notifies"]/args_add_block[descendant::symbol/ident/@value="restart"]/descendant::method_add_arg[fcall/ident/@value="resources"]/descendant::assoc_new[symbol/ident/@value="service"]/descendant::tstring_content').select{|notifies| @coreservices.include?(notifies.attribute('value').to_s)} end end rule "ETSY006", "Execute resource used to run chef-provided command" do tags %w{style recipe etsy} recipe do |ast| find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s @corecommands.any? { |cmd| cmd_str.include? cmd } end.map{|cmd| match(cmd)} end end rule "ETSY007", "Package or yum_package resource used to install core package without specific version number" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd).include? svc } end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd).include? svc } end pres.concat(ypres).map{|cmd| match(cmd)} end end Added rules ETSY006 and ETSY007 and added to README #Etsy Foodcritic rules @coreservices = ["httpd", "mysql", "memcached", "postgresql-server"] @coreservicepackages = ["httpd", "Percona-Server-server-51", "memcached", "postgresql-server"] @corecommands = ["yum -y", "yum install", "yum reinstall", "yum remove", "mkdir", "useradd", "usermod", "touch"] rule "ETSY001", "Package or yum_package resource used with :upgrade action" do tags %w{correctness recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end pres.concat(ypres).map{|cmd| match(cmd)} end end rule "ETSY002", "Execute resource used to run git commands" do tags %w{style recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s cmd_str.include?('git ') end.map{|cmd| match(cmd)} end end rule "ETSY003", "Execute resource used to run curl or wget commands" do tags %w{style recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s (cmd_str.include?('curl ') || cmd_str.include?('wget ')) end.map{|cmd| match(cmd)} end end # This rule does not detect execute resources defined inside a conditional, as foodcritic rule FC023 (Prefer conditional attributes) # already provides this. It's recommended to use both rules in conjunction. (foodcritic -t etsy,FC023) rule "ETSY004", "Execute resource defined without conditional or action :nothing" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_actions = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s condition = cmd.xpath('//ident[@value="only_if" or @value="not_if" or @value="creates"][parent::fcall or parent::command or ancestor::if]') (condition.empty? && !cmd_actions.include?("nothing")) end.map{|cmd| match(cmd)} end end rule "ETSY005", "Action :restart sent to a core service" do tags %w{style recipe etsy} recipe do |ast, filename| ast.xpath('//command[ident/@value = "notifies"]/args_add_block[descendant::symbol/ident/@value="restart"]/descendant::method_add_arg[fcall/ident/@value="resources"]/descendant::assoc_new[symbol/ident/@value="service"]/descendant::tstring_content').select{|notifies| @coreservices.include?(notifies.attribute('value').to_s)} end end rule "ETSY006", "Execute resource used to run chef-provided command" do tags %w{style recipe etsy} recipe do |ast| find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s @corecommands.any? { |cmd| cmd_str.include? cmd } end.map{|cmd| match(cmd)} end end rule "ETSY007", "Package or yum_package resource used to install core package without specific version number" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd).include? svc } end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd).include? svc } end pres.concat(ypres).map{|cmd| match(cmd)} end end
#Etsy Foodcritic rules @coreservices = ["httpd", "mysql", "memcached", "postgresql-server"] @coreservicepackages = ["httpd", "Percona-Server-server-51", "memcached", "postgresql-server"] @corecommands = ["yum -y", "yum install", "yum reinstall", "yum remove", "mkdir", "useradd", "usermod", "touch"] rule "ETSY001", "Package or yum_package resource used with :upgrade action" do tags %w{correctness recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end pres.concat(ypres).map{|cmd| match(cmd)} end end #ETSY002 and ETSY003 removed as they were added to mainline foodcritic as FC040 and FC041 # This rule does not detect execute resources defined inside a conditional, as foodcritic rule FC023 (Prefer conditional attributes) # already provides this. It's recommended to use both rules in conjunction. (foodcritic -t etsy,FC023) rule "ETSY004", "Execute resource defined without conditional or action :nothing" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_actions = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s condition = cmd.xpath('//ident[@value="only_if" or @value="not_if" or @value="creates"][parent::fcall or parent::command or ancestor::if]') (condition.empty? && !cmd_actions.include?("nothing")) end.map{|cmd| match(cmd)} end end rule "ETSY005", "Action :restart sent to a core service" do tags %w{style recipe etsy} recipe do |ast, filename| find_resources(ast).select do |resource| notifications(resource).any? do |notification| @coreservices.include?(notification[:resource_name]) and notification[:action] == :restart end end end end rule "ETSY006", "Execute resource used to run chef-provided command" do tags %w{style recipe etsy} recipe do |ast| find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s @corecommands.any? { |corecommand| cmd_str.include? corecommand } end.map{|c| match(c)} end end rule "ETSY007", "Package or yum_package resource used to install core package without specific version number" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_action = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd) == svc } && cmd_action.include?('install') end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_action = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd) == svc } && cmd_action.include?('install') end pres.concat(ypres).map{|cmd| match(cmd)} end end Fix issue #4 by creating a new Nokogiri::XML object before xpath query. #Etsy Foodcritic rules @coreservices = ["httpd", "mysql", "memcached", "postgresql-server"] @coreservicepackages = ["httpd", "Percona-Server-server-51", "memcached", "postgresql-server"] @corecommands = ["yum -y", "yum install", "yum reinstall", "yum remove", "mkdir", "useradd", "usermod", "touch"] rule "ETSY001", "Package or yum_package resource used with :upgrade action" do tags %w{correctness recipe etsy} recipe do |ast| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str.include?('upgrade') end pres.concat(ypres).map{|cmd| match(cmd)} end end #ETSY002 and ETSY003 removed as they were added to mainline foodcritic as FC040 and FC041 # This rule does not detect execute resources defined inside a conditional, as foodcritic rule FC023 (Prefer conditional attributes) # already provides this. It's recommended to use both rules in conjunction. (foodcritic -t etsy,FC023) rule "ETSY004", "Execute resource defined without conditional or action :nothing" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'execute').find_all do |cmd| cmd_actions = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s condition = Nokogiri::XML(cmd.to_xml).xpath('//ident[@value="only_if" or @value="not_if" or @value="creates"][parent::fcall or parent::command or ancestor::if]') (condition.empty? && !cmd_actions.include?("nothing")) end.map{|cmd| match(cmd)} end end rule "ETSY005", "Action :restart sent to a core service" do tags %w{style recipe etsy} recipe do |ast, filename| find_resources(ast).select do |resource| notifications(resource).any? do |notification| @coreservices.include?(notification[:resource_name]) and notification[:action] == :restart end end end end rule "ETSY006", "Execute resource used to run chef-provided command" do tags %w{style recipe etsy} recipe do |ast| find_resources(ast, :type => 'execute').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'command') || resource_name(cmd)).to_s @corecommands.any? { |corecommand| cmd_str.include? corecommand } end.map{|c| match(c)} end end rule "ETSY007", "Package or yum_package resource used to install core package without specific version number" do tags %w{style recipe etsy} recipe do |ast,filename| pres = find_resources(ast, :type => 'package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_action = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd) == svc } && cmd_action.include?('install') end ypres = find_resources(ast, :type => 'yum_package').find_all do |cmd| cmd_str = (resource_attribute(cmd, 'version') || resource_name(cmd)).to_s cmd_action = (resource_attribute(cmd, 'action') || resource_name(cmd)).to_s cmd_str == resource_name(cmd) && @coreservicepackages.any? { |svc| resource_name(cmd) == svc } && cmd_action.include?('install') end pres.concat(ypres).map{|cmd| match(cmd)} end end
require 'sinatra' require 'nokogiri' require 'phantomjs' # Rewrite urls to absolute urls # And what madness. Also escaping url for cases for where # people are including unescaped urls # N.B. modifies doc def convert_to_absolute_urls!(doc, url, selector, attribute) # If there's a base tag in the document it should override # the base url to be used for relative urls if doc.at('head base') url = URI(url) + doc.at('head base')['href'] end doc.search(selector).each do |node| node[attribute] = URI(url) + URI.escape(node[attribute]) end end # In a given bit of text which is css convert all urls # to be absolute def in_css_make_urls_absolute(css, base_url) css.gsub(/url\((.*)\)/) do |c| url = base_url + $1 "url(#{url})" end end # Will also install phantomjs if it's not already there Phantomjs.path get '/proxy' do url = params['url'] || 'http://localhost:4567/example_dynamic_page' # This super naive proxying doesn't pass through error codes or headers content = Phantomjs.run('./phantomjs/get.js', url) # Strip script tags doc = Nokogiri.HTML(content) doc.search('script').remove convert_to_absolute_urls!(doc, url, 'img', 'src') convert_to_absolute_urls!(doc, url, 'link', 'href') convert_to_absolute_urls!(doc, url, 'a', 'href') # Rewrite links to point at the proxy doc.search('a').each do |node| node['href'] = "/proxy?url=" + CGI.escape(node['href']) end # Find all embedded css in style attributes doc.search('*[style]').each do |node| # TODO Actually pass a proper base url which takes into account # a base override node['style'] = in_css_make_urls_absolute(node['style'], url) end doc.to_s end # An example dynamic page that can be used to demonstrate the # proxy. This page is a simple page that gets loaded via javascript # (in this case React). get '/example_dynamic_page' do haml :example_dynamic_page end Extract method require 'sinatra' require 'nokogiri' require 'phantomjs' # Rewrite urls to absolute urls # And what madness. Also escaping url for cases for where # people are including unescaped urls # N.B. modifies doc def convert_to_absolute_urls!(doc, url, selector, attribute) # If there's a base tag in the document it should override # the base url to be used for relative urls url = html_base_url(doc, url) doc.search(selector).each do |node| node[attribute] = URI(url) + URI.escape(node[attribute]) end end # In a given bit of text which is css convert all urls # to be absolute def in_css_make_urls_absolute(css, base_url) css.gsub(/url\((.*)\)/) do |c| url = base_url + $1 "url(#{url})" end end def html_base_url(doc, url) if doc.at('head base') URI(url) + doc.at('head base')['href'] else url end end # Will also install phantomjs if it's not already there Phantomjs.path get '/proxy' do url = params['url'] || 'http://localhost:4567/example_dynamic_page' # This super naive proxying doesn't pass through error codes or headers content = Phantomjs.run('./phantomjs/get.js', url) # Strip script tags doc = Nokogiri.HTML(content) doc.search('script').remove convert_to_absolute_urls!(doc, url, 'img', 'src') convert_to_absolute_urls!(doc, url, 'link', 'href') convert_to_absolute_urls!(doc, url, 'a', 'href') # Rewrite links to point at the proxy doc.search('a').each do |node| node['href'] = "/proxy?url=" + CGI.escape(node['href']) end # Find all embedded css in style attributes doc.search('*[style]').each do |node| # TODO Actually pass a proper base url which takes into account # a base override node['style'] = in_css_make_urls_absolute(node['style'], url) end doc.to_s end # An example dynamic page that can be used to demonstrate the # proxy. This page is a simple page that gets loaded via javascript # (in this case React). get '/example_dynamic_page' do haml :example_dynamic_page end
require 'feedjira' class Feed autoload :Discovery, 'feed/discovery' autoload :Image, 'feed/image' autoload :Item, 'feed/item' autoload :S3, 'feed/s3' class << self def update_all Source.where(kind: 'blog').each do |source| new(source).update end end end attr_reader :source, :logger def initialize(source, options = {}) @source = source @logger = options[:logger] || Logger.new(STDOUT) Feed::S3.setup(access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']) end def update source.update_attributes!(title: discover_title) unless source.title.present? source.feed_url = discover_feed_url unless source.feed_url.present? update_entries source.save! if source.feed_url_changed? && source.feed_url != source.url rescue => e puts e.message puts e.backtrace end private def discover_title title = Discovery.new(source.url, logger: logger).title logger.info "discovered title for #{source.url}: #{title}" title end def discover_feed_url urls = Discovery.new(source.url, logger: logger).feed_urls url = urls.reject { |url| url =~ /comment/ }.first logger.info "discovered feed url for #{source.url}: #{url}" if url url || source.url end def update_entries parse.entries.each do |data| item = Item.new(source.url, source.team_id, data) raise "can not find guid for item in source #{source.feed_url}" unless item.guid # logger.info "processing item #{item.guid}: #{item.title}" record = Activity.where(:guid => item.guid).first attrs = item.attrs.merge(img_url: record.try(:img_url) || Image.new(item.url, logger: logger).store) record ? record.update_attributes!(attrs) : Activity.create!(attrs) end end def parse silence_warnings do logger.info "Feeds: going to fetch #{source.feed_url}" data = Feedjira::Feed.fetch_and_parse(source.feed_url) logger.info "this does not look like a valid feed" unless data.respond_to?(:entries) data end end end resuce update_entries and log error require 'feedjira' class Feed autoload :Discovery, 'feed/discovery' autoload :Image, 'feed/image' autoload :Item, 'feed/item' autoload :S3, 'feed/s3' class << self def update_all Source.where(kind: 'blog').each do |source| new(source).update end end end attr_reader :source, :logger def initialize(source, options = {}) @source = source @logger = options[:logger] || Logger.new(STDOUT) Feed::S3.setup(access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']) end def update source.update_attributes!(title: discover_title) unless source.title.present? source.feed_url = discover_feed_url unless source.feed_url.present? update_entries source.save! if source.feed_url_changed? && source.feed_url != source.url rescue => e puts e.message puts e.backtrace end private def discover_title title = Discovery.new(source.url, logger: logger).title logger.info "discovered title for #{source.url}: #{title}" title end def discover_feed_url urls = Discovery.new(source.url, logger: logger).feed_urls url = urls.reject { |url| url =~ /comment/ }.first logger.info "discovered feed url for #{source.url}: #{url}" if url url || source.url end def update_entries parse.entries.each do |data| item = Item.new(source.url, source.team_id, data) raise "can not find guid for item in source #{source.feed_url}" unless item.guid # logger.info "processing item #{item.guid}: #{item.title}" record = Activity.where(:guid => item.guid).first attrs = item.attrs.merge(img_url: record.try(:img_url) || Image.new(item.url, logger: logger).store) record ? record.update_attributes!(attrs) : Activity.create!(attrs) end rescue => e logger.error "Could not update entries: #{e.message}" nil end def parse logger.info "Feeds: going to fetch #{source.feed_url}" data = Feedjira::Feed.fetch_and_parse(source.feed_url) logger.info "this does not look like a valid feed" unless data.respond_to?(:entries) data end end
Add feed class to lib class Feed attr_accessor :feed def initialize(raw_feed) @feed = [] add(raw_feed) end def add(raw_feed) @feed = @feed + clean_feed(raw_feed) end def clean_feed(raw_feed) remove_links(filter_out_crap(raw_feed)) end def filter_out_crap(raw_feed) raw_feed.reject do |tweet| (tweet.full_text[0] == '@') || (tweet.full_text[0..3] == 'RT @') || (tweet.full_text[1] == '@') end end def remove_links(raw_feed) raw_feed.map do |tweet| tweet.full_text.gsub(/(https?:[\w|\/|\.|\?|\&]+)/i, '') end end end
# # Cookbook Name:: monit # Resource:: check # require 'chef/resource' class Chef class Resource # rubocop: disable ClassLength class MonitCheck < Chef::Resource identity_attr :name def initialize(name, run_context = nil) super @resource_name = :monit_check @provider = Chef::Provider::MonitCheck @action = :create @allowed_actions = [:create, :remove] @name = name end def cookbook(arg = nil) set_or_return( :cookbook, arg, :kind_of => String, :default => 'monit' ) end def check_type(arg = nil) set_or_return( :check_type, arg, :kind_of => String, :equal_to => check_pairs.keys, :default => 'process' ) end def check_id(arg = nil) set_or_return( :check_id, arg, :kind_of => String, :required => true ) end # rubocop: disable MethodLength def id_type(arg = nil) set_or_return( :id_type, arg, :kind_of => String, :equal_to => check_pairs.values, :default => check_pairs[check_type], :callbacks => { 'is a valid id_type for check_type' => lambda do |spec| spec == check_pairs[check_type] end, } ) end # rubocop: enable MethodLength def start_as(arg = nil) set_or_return( :start_as, arg, :kind_of => String ) end def start(arg = nil) set_or_return( :start, arg, :kind_of => String, :callbacks => { 'does not exceed max arg length' => lambda do |spec| spec.length < 127 end, } ) end def stop(arg = nil) set_or_return( :stop, arg, :kind_of => String, :callbacks => { 'does not exceed max arg length' => lambda do |spec| spec.length < 127 end, } ) end def group(arg = nil) set_or_return( :group, arg, :kind_of => String ) end def tests(arg = nil) set_or_return( :tests, arg, :kind_of => Array, :default => [] ) end def every(arg = nil) set_or_return( :every, arg, :kind_of => String ) end private def check_pairs { 'process' => 'pidfile', 'procmatch' => 'matching', 'file' => 'path', 'fifo' => 'path', 'filesystem' => 'path', 'directory' => 'path', 'host' => 'address', 'system' => nil, 'program' => 'path' } end end # rubocop: enable ClassLength end end fix cookbook source for monit_check # # Cookbook Name:: monit # Resource:: check # require 'chef/resource' class Chef class Resource # rubocop: disable ClassLength class MonitCheck < Chef::Resource identity_attr :name def initialize(name, run_context = nil) super @resource_name = :monit_check @provider = Chef::Provider::MonitCheck @action = :create @allowed_actions = [:create, :remove] @name = name end def cookbook(arg = nil) set_or_return( :cookbook, arg, :kind_of => String, :default => 'monit-ng' ) end def check_type(arg = nil) set_or_return( :check_type, arg, :kind_of => String, :equal_to => check_pairs.keys, :default => 'process' ) end def check_id(arg = nil) set_or_return( :check_id, arg, :kind_of => String, :required => true ) end # rubocop: disable MethodLength def id_type(arg = nil) set_or_return( :id_type, arg, :kind_of => String, :equal_to => check_pairs.values, :default => check_pairs[check_type], :callbacks => { 'is a valid id_type for check_type' => lambda do |spec| spec == check_pairs[check_type] end, } ) end # rubocop: enable MethodLength def start_as(arg = nil) set_or_return( :start_as, arg, :kind_of => String ) end def start(arg = nil) set_or_return( :start, arg, :kind_of => String, :callbacks => { 'does not exceed max arg length' => lambda do |spec| spec.length < 127 end, } ) end def stop(arg = nil) set_or_return( :stop, arg, :kind_of => String, :callbacks => { 'does not exceed max arg length' => lambda do |spec| spec.length < 127 end, } ) end def group(arg = nil) set_or_return( :group, arg, :kind_of => String ) end def tests(arg = nil) set_or_return( :tests, arg, :kind_of => Array, :default => [] ) end def every(arg = nil) set_or_return( :every, arg, :kind_of => String ) end private def check_pairs { 'process' => 'pidfile', 'procmatch' => 'matching', 'file' => 'path', 'fifo' => 'path', 'filesystem' => 'path', 'directory' => 'path', 'host' => 'address', 'system' => nil, 'program' => 'path' } end end # rubocop: enable ClassLength end end
require 'csv' require 'fileutils' require 'set' def create_crag_page(crags) # determine unique metros metros = Set[] states = Set[] local_crags = Hash.new state_locals = Hash.new #TODO needs to loop through each metros cell crags.each do |crag| metros.add(crag["metros"]) states.add(crag["state"]) end # determine the locales in each state states.each do |state| state_locals[state] = Set[] end #TODO combine into original crag loop? crags.each do |crag| state_locals[crag["state"]].add(crag["name"]) end File.open("crags.html","w") do |f| f << "---\n" f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n" f << "layout: page\n" f << "title: Crag Conditions\n" f << "description: Real-time, precipitation-focused reports of current, past, and forecasted climbing weather for local climbing crags\n" f << "---\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n" f << 'precipitation-focused reports of current, past, and future climbing weather for crags located in the United States, sourced'+"\n" f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n" f << "</section>\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<h2 class="bb b--moon-gray">Crags by Nearest Metro</h2>'+"\n" f << '<ul class="list pl3 f6 mt2">'+"\n" metros.each do |metro| metro_slug = metro.gsub(',', '').gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase f << '<li><a class="no-underline fancy-link relative black-70 hover-light-red" href="/crags/' + metro_slug + '-weather.html">' + metro + "</a></li>\n" end f << "</ul>\n" f << '<h2 class="bb b--moon-gray">Crag by State</h2>'+"\n" state_locals.each do |state, crags| f << '<h3 class="mb2">' + state + "</h3>\n" f << '<ul class="list pl3 f6 mt2">'+"\n" crags.each do |crag| crag_slug = crag.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + '-' + state.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase f << '<li><a class="no-underline fancy-link relative black-70 hover-light-red" href="/crags/' + crag_slug + '-weather.html">' + crag + "</a></li>\n" end f << "</ul>\n" end f << "</section>\n" end end def create_crags(crags) crags.each do |crag| slug = crag["name"].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + "-" + crag["state"].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase File.open("_crags/" + slug + "-weather.md","w") do |f| f << "---\n" f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n" f << "layout: page\n" f << "title: " + crag["name"] + " Current, Past, and Forecasted Weather\n" f << "title_override: " + crag["name"] + " Weather\n" f << "description: Real-time, precipitation-focused reports of current, past, and forecasted climbing weather for " + crag["name"] + ', ' + crag["state"] + "\n" f << "js_includes:\n" f << " - weather.js\n" f << "---\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n" f << 'precipitation-focused reports of current, past, and forecasted climbing weather for ' + crag["name"] + ', ' + crag["state"] + ', sourced'+"\n" f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n" f << "</section>\n\n" f << '<p id="settings-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Instructions</p>'+"\n" f << '<section id="settings" class="overflow-hidden" style="display:none;">'+"\n" f << ' <div class="mv2 ph2 center">'+"\n" f << ' <div class="fn f6 tc pv2">'+"\n" f << ' <p class="measure lh-copy center"><strong>Show/hide hourly forecasts</strong> by clicking the desired day.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Current and Past conditions</strong> are measured by the nearest weather station. <strong>Forecast conditions</strong> are calculated and polled separately.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Having issues?</strong> Try <a id="clear-cache" class="no-underline relative fancy-link light-red hover-light-red" href="#">clearing the local cache</a>.</p>'+"\n" f << " </div>\n" f << " </div>\n" f << "</section>\n" f << '<section id="weather" data-crag="' + slug + '" class="mv4-ns mv3 ph2 center"></section>'+"\n" f << '<p id="issues-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Known Issues</p>'+"\n" f << '<section id="issues" class="overflow-hidden tc f6">'+"\n" f << "</section>\n\n" end File.open("assets/json/crags/" + slug + ".json","w") do |f| f << "[\n" f << " {\n" f << ' "name": "' + crag["name"] + '",'+"\n" f << ' "note": "' + crag["note"] + '",'+"\n" f << ' "mountainProject": "' + crag["url"] + '",'+"\n" f << ' "station": "' + crag["station"] + '",'+"\n" f << ' "office": "' + crag["office"] + '",'+"\n" f << ' "coordinates": ['+"\n" f << " " + crag["lat"] + ",\n" f << " " + crag["long"] + "\n" f << " ]\n" f << " }\n" f << "]" end end end def create_metros(crags) # determine unique metros metros = Set[] local_crags = Hash.new #TODO needs to loop through each metros cell crags.each do |crag| metros.add(crag["metros"]) end # determine the crags near them metros.each do |metro| local_crags[metro] = []; end crags.each do |crag| local_crags[crag["metros"]].push({ name: crag["name"], note: crag["note"], url: crag["url"], station: crag["station"], office: crag["office"], lat: crag["lat"], long: crag["long"] }) end local_crags.each do |metro, crags| slug = metro.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase File.open("assets/json/crags/" + slug + ".json","w") do |f| f << "[\n" crags.each do |crag| f << " {\n" f << ' "name": "' + crag[:name] + '",'+"\n" f << ' "note": "' + crag[:note] + '",'+"\n" f << ' "mountainProject": "' + crag[:url] + '",'+"\n" f << ' "station": "' + crag[:station] + '",'+"\n" f << ' "office": "' + crag[:office] + '",'+"\n" f << ' "coordinates": ['+"\n" f << " " + crag[:lat] + ",\n" f << " " + crag[:long] + "\n" f << " ]\n" f << " }" if crag != crags.last f << ",\n" else f << "\n" end end f << "]" end end metros.each do |metro| slug = metro.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase File.open("_crags/" + slug + "-weather.md","w") do |f| f << "---\n" f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n" f << "layout: page\n" f << "title: " + metro + " Current, Past, and Forecasted Climbing Weather\n" f << "title_override: " + metro + " Weather\n" f << "description: Real-time, precipitation-focused reports of current, past, and forecasted climbing weather for crags near " + metro + "\n" f << "js_includes:\n" f << " - weather.js\n" f << "---\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n" f << 'precipitation-focused reports of current, past, and forecasted climbing weather for crags near ' + metro + ', sourced'+"\n" f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n" f << "</section>\n\n" f << '<p id="settings-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Settings</p>'+"\n" f << '<section id="settings" class="overflow-hidden" style="display:none;">'+"\n" f << ' <div class="mv2 ph2 center">'+"\n" f << ' <div id="menu" class="fn fl-ns w-50-l w-100 pv2 pr4-l">'+"\n" f << ' <div class="f7 tc b">Select Defaults:</div>'+"\n" f << " </div>\n" f << ' <div class="fn f6 tc fl-ns w-50-l w-100 pv2">'+"\n" f << ' <span class="f7 b">Instructions:</span>'+"\n" f << ' <p class="measure lh-copy center"><strong>Show/hide crags</strong> by clicking on their name to the left; green mean shown and gray means hidden.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Show/hide hourly forecasts</strong> by clicking the desired day.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Current and Past conditions</strong> are measured by the nearest weather station. <strong>Forecast conditions</strong> are calculated and polled separately.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Having issues?</strong> Try <a id="clear-cache" class="no-underline relative fancy-link light-red hover-light-red" href="#">clearing the local cache</a>.</p>'+"\n" f << " </div>\n" f << " </div>\n" f << "</section>\n" f << '<section id="weather" data-crag="' + slug + '" class="mv4-ns mv3 ph2 center"></section>'+"\n" f << '<p id="issues-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Known Issues</p>'+"\n" f << '<section id="issues" class="overflow-hidden tc f6">'+"\n" f << "</section>\n\n" end end end crags = CSV.read("crags.csv", headers: true) # clear the old crags markdown files Dir.foreach('_crags') do |f| fn = File.join('_crags', f) File.delete(fn) if f != '.' && f != '..' end # clear the old crags json files Dir.foreach('assets/json/crags') do |f| fn = File.join('assets/json/crags', f) File.delete(fn) if f != '.' && f != '..' end create_crag_page(crags) create_crags(crags) create_metros(crags) improve crag descriptions require 'csv' require 'fileutils' require 'set' def create_crag_page(crags) # determine unique metros metros = Set[] states = Set[] local_crags = Hash.new state_locals = Hash.new #TODO needs to loop through each metros cell crags.each do |crag| metros.add(crag["metros"]) states.add(crag["state"]) end # determine the locales in each state states.each do |state| state_locals[state] = Set[] end #TODO combine into original crag loop? crags.each do |crag| state_locals[crag["state"]].add(crag["name"]) end File.open("crags.html","w") do |f| f << "---\n" f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n" f << "layout: page\n" f << "title: Crag Conditions\n" f << "description: Real-time, precipitation-focused reports of current, past, and forecasted climbing weather for local climbing crags\n" f << "---\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n" f << 'precipitation-focused reports of current, past, and future climbing weather for crags located in the United States, sourced'+"\n" f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n" f << "</section>\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<h2 class="bb b--moon-gray">Crags by Nearest Metro</h2>'+"\n" f << '<ul class="list pl3 f6 mt2">'+"\n" metros.each do |metro| metro_slug = metro.gsub(',', '').gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase f << '<li><a class="no-underline fancy-link relative black-70 hover-light-red" href="/crags/' + metro_slug + '-weather.html">' + metro + "</a></li>\n" end f << "</ul>\n" f << '<h2 class="bb b--moon-gray">Crag by State</h2>'+"\n" state_locals.each do |state, crags| f << '<h3 class="mb2">' + state + "</h3>\n" f << '<ul class="list pl3 f6 mt2">'+"\n" crags.each do |crag| crag_slug = crag.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + '-' + state.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase f << '<li><a class="no-underline fancy-link relative black-70 hover-light-red" href="/crags/' + crag_slug + '-weather.html">' + crag + "</a></li>\n" end f << "</ul>\n" end f << "</section>\n" end end def create_crags(crags) crags.each do |crag| slug = crag["name"].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase + "-" + crag["state"].gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase File.open("_crags/" + slug + "-weather.md","w") do |f| f << "---\n" f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n" f << "layout: page\n" f << "title: " + crag["name"] + " Current, Past, and Forecasted Weather\n" f << "title_override: " + crag["name"] + " Weather\n" f << "description: A lightweight climbing weather report for " + crag["name"] + ', ' + crag["state"] + ". Optimized for poor connections.\n" f << "js_includes:\n" f << " - weather.js\n" f << "---\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n" f << 'precipitation-focused reports of current, past, and forecasted climbing weather for ' + crag["name"] + ', ' + crag["state"] + ', sourced'+"\n" f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n" f << "</section>\n\n" f << '<p id="settings-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Instructions</p>'+"\n" f << '<section id="settings" class="overflow-hidden" style="display:none;">'+"\n" f << ' <div class="mv2 ph2 center">'+"\n" f << ' <div class="fn f6 tc pv2">'+"\n" f << ' <p class="measure lh-copy center"><strong>Show/hide hourly forecasts</strong> by clicking the desired day.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Current and Past conditions</strong> are measured by the nearest weather station. <strong>Forecast conditions</strong> are calculated and polled separately.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Having issues?</strong> Try <a id="clear-cache" class="no-underline relative fancy-link light-red hover-light-red" href="#">clearing the local cache</a>.</p>'+"\n" f << " </div>\n" f << " </div>\n" f << "</section>\n" f << '<section id="weather" data-crag="' + slug + '" class="mv4-ns mv3 ph2 center"></section>'+"\n" f << '<p id="issues-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Known Issues</p>'+"\n" f << '<section id="issues" class="overflow-hidden tc f6">'+"\n" f << "</section>\n\n" end File.open("assets/json/crags/" + slug + ".json","w") do |f| f << "[\n" f << " {\n" f << ' "name": "' + crag["name"] + '",'+"\n" f << ' "note": "' + crag["note"] + '",'+"\n" f << ' "mountainProject": "' + crag["url"] + '",'+"\n" f << ' "station": "' + crag["station"] + '",'+"\n" f << ' "office": "' + crag["office"] + '",'+"\n" f << ' "coordinates": ['+"\n" f << " " + crag["lat"] + ",\n" f << " " + crag["long"] + "\n" f << " ]\n" f << " }\n" f << "]" end end end def create_metros(crags) # determine unique metros metros = Set[] local_crags = Hash.new #TODO needs to loop through each metros cell crags.each do |crag| metros.add(crag["metros"]) end # determine the crags near them metros.each do |metro| local_crags[metro] = []; end crags.each do |crag| local_crags[crag["metros"]].push({ name: crag["name"], note: crag["note"], url: crag["url"], station: crag["station"], office: crag["office"], lat: crag["lat"], long: crag["long"] }) end local_crags.each do |metro, crags| slug = metro.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase File.open("assets/json/crags/" + slug + ".json","w") do |f| f << "[\n" crags.each do |crag| f << " {\n" f << ' "name": "' + crag[:name] + '",'+"\n" f << ' "note": "' + crag[:note] + '",'+"\n" f << ' "mountainProject": "' + crag[:url] + '",'+"\n" f << ' "station": "' + crag[:station] + '",'+"\n" f << ' "office": "' + crag[:office] + '",'+"\n" f << ' "coordinates": ['+"\n" f << " " + crag[:lat] + ",\n" f << " " + crag[:long] + "\n" f << " ]\n" f << " }" if crag != crags.last f << ",\n" else f << "\n" end end f << "]" end end metros.each do |metro| slug = metro.gsub(' ', '-').gsub(/[^\w-]/, '').gsub(/(-){2,}/, '-').downcase File.open("_crags/" + slug + "-weather.md","w") do |f| f << "---\n" f << "### THIS FILE IS AUTO-GENERATED - DO NOT EDIT ###\n" f << "layout: page\n" f << "title: " + metro + " Current, Past, and Forecasted Climbing Weather\n" f << "title_override: " + metro + " Weather\n" f << "description: A lightweight climbing weather report for crags near " + metro + ". Optimized for poor connections.\n" f << "js_includes:\n" f << " - weather.js\n" f << "---\n\n" f << '<section class="measure center lh-copy f5-ns f6 ph2 mv4" style="text-align: justify;">'+"\n" f << '<strong>"Is it dry?"</strong>, an oft-repeated, age-old question. Here are real-time,'+"\n" f << 'precipitation-focused reports of current, past, and forecasted climbing weather for crags near ' + metro + ', sourced'+"\n" f << 'from <a class="no-underline fancy-link relative light-red" target="_blank" href="https://www.weather.gov/documentation/services-web-api">weather.gov</a>.'+"\n" f << "</section>\n\n" f << '<p id="settings-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Settings</p>'+"\n" f << '<section id="settings" class="overflow-hidden" style="display:none;">'+"\n" f << ' <div class="mv2 ph2 center">'+"\n" f << ' <div id="menu" class="fn fl-ns w-50-l w-100 pv2 pr4-l">'+"\n" f << ' <div class="f7 tc b">Select Defaults:</div>'+"\n" f << " </div>\n" f << ' <div class="fn f6 tc fl-ns w-50-l w-100 pv2">'+"\n" f << ' <span class="f7 b">Instructions:</span>'+"\n" f << ' <p class="measure lh-copy center"><strong>Show/hide crags</strong> by clicking on their name to the left; green mean shown and gray means hidden.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Show/hide hourly forecasts</strong> by clicking the desired day.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Current and Past conditions</strong> are measured by the nearest weather station. <strong>Forecast conditions</strong> are calculated and polled separately.</p>'+"\n" f << ' <hr class="mw5 p0 mv2 o-60 b0 bt b--light-red light-red bg-light-red">'+"\n" f << ' <p class="measure lh-copy center"><strong>Having issues?</strong> Try <a id="clear-cache" class="no-underline relative fancy-link light-red hover-light-red" href="#">clearing the local cache</a>.</p>'+"\n" f << " </div>\n" f << " </div>\n" f << "</section>\n" f << '<section id="weather" data-crag="' + slug + '" class="mv4-ns mv3 ph2 center"></section>'+"\n" f << '<p id="issues-toggle" class="mw5 b center tc hover-light-red black-70 pointer">Show Known Issues</p>'+"\n" f << '<section id="issues" class="overflow-hidden tc f6">'+"\n" f << "</section>\n\n" end end end crags = CSV.read("crags.csv", headers: true) # clear the old crags markdown files Dir.foreach('_crags') do |f| fn = File.join('_crags', f) File.delete(fn) if f != '.' && f != '..' end # clear the old crags json files Dir.foreach('assets/json/crags') do |f| fn = File.join('assets/json/crags', f) File.delete(fn) if f != '.' && f != '..' end create_crag_page(crags) create_crags(crags) create_metros(crags)
require 'redis/connection/hiredis' require 'redis' require 'digest/md5' class Classifier attr_accessor :scope, :filter_size, :categories, :categories_total, :weight, :ap BLOOMSIZE = 2**24 ######################## # init def initialize(scope, options = {filter_size: BLOOMSIZE, weight: 1.0, ap: 0.5}) @r = Redis.new(host: "localhost", port: 6379) @scope = scope scope_data = @r.hgetall(scope_key) @weight = scope_data["weight"].to_f || options["weight"] @ap = scope_data["ap"].to_f || options["ap"] @filter_size = scope_data["filter_size"].to_i || options[:filter_size] @categories = {} scope_data.select{ |k,v| k =~ /^C:.*/ }.each_pair{|k,v| @categories[k.gsub(/C:/, "")] = v.to_i } @categories_total = categories.inject(0) { |sum, hash| sum += hash[1] } end def save @r.hmset scope_key, "filter_size", @filter_size, "weight", weight, "ap", ap end ######################### # train def untrain_phrase(phrase, categories) train_phrase(phrase, categories) end def train_phrase(phrase, categories) train(phrase_to_words(phrase), categories) end def train(words, categories) categories.each do |category| words.each { |word| update_word(word, category) } update_category(category) end end ########################### # access bloom filter data def update_word(word, category) indexes(word).each { |index| update_index(category, index) } end def indexes(word) [ word, word+"2", word+"3"].map { |word| Digest::MD5.hexdigest(word).to_i(16) }.map { |index| index % @filter_size } end def update_index(category, index) oldvalue = @r.getrange(category, index, index) value = 1 value = oldvalue.getbyte(0) + 1 if oldvalue && oldvalue.length > 0 @r.setrange(category_key(category), index, value.chr) end def update_category(category) @r.hincrby(scope_key, category_key(category), 1) end def get_wordcount(category, word) indexes(word).map { |index| val = @r.getrange(category, index, index) val.length > 0 ? val.getbyte(0) : 0 }.min end ############################# # BLOOMfilter - implementation def bloom_result_for_word(word_count, category_count, totals) return 0.0 unless category_count word_prob = word_count.to_f / category_count.to_f ((weight * ap) + (totals * word_prob)) / (weight + totals) end def bloom_result(phrase) words = phrase_to_words(phrase) totals = Hash.new(0.0) word_counts = {} data = {} @categories.each_key do |category| word_counts[category] = Hash.new(0.0) words.each { |word| word_counts[category][word] = get_wordcount(category, word) totals[word] += word_counts[category][word] } end @categories.each_key do |category| data[category] = words.inject(1.0) { |p, word| p *= bloom_result_for_word(word_counts[category][word], categories[category], totals[word]) } data[category] *= (categories / categories_total) end # normalize max = data.values.max max = 1.0/max data.each_pair { |category, rank| data[category] *= max } data end private def scope_key "S:#{scope}" end def category_key category "C:#{category}" end def bloom_key category "B:#{scope}:#{category}" end def phrase_to_words(phrase) phrase.unpack('C*').pack('U*').gsub(/[^\w]/, " ").split.inject([]){|data, w| data << w.downcase}.uniq end end Refactored and fixed calculation algorithm and naming, still needs heavy optimaziation require 'redis/connection/hiredis' require 'redis' require 'digest/md5' class Classifier attr_accessor :scope, :filter_size, :categories, :categories_total, :weight, :ap, :r BLOOMSIZE = 2**24 ######################## # init def initialize(scope, options = {filter_size: BLOOMSIZE, weight: 1.0, ap: 0.5}) @r = Redis.new(host: "localhost", port: 6379) @scope = scope scope_data = @r.hgetall(scope_key) @weight = scope_data["weight"].to_f || options["weight"] @ap = scope_data["ap"].to_f || options["ap"] @filter_size = scope_data["filter_size"].to_i || options[:filter_size] @categories = {} scope_data.select{ |k,v| k =~ /^C:.*/ }.each_pair{|k,v| @categories[k.gsub(/C:/, "")] = v.to_i } @categories_total = categories.inject(0) { |sum, hash| sum += hash[1] } end def save @r.hmset scope_key, "filter_size", @filter_size, "weight", weight, "ap", ap end ######################### # train def untrain_phrase(phrase, categories) # train_phrase(phrase, categories) end def train_phrase(phrase, categories) train(phrase_to_words(phrase), categories) end def train(words, categories) categories.each do |category| words.each { |word| update_word(word, category) } update_category(category) end end ########################### # access bloom filter data def update_word(word, category) indexes(word).each { |index| update_index(category, index) } end def indexes(word) [ word, word+"2", word+"3"]. map { |hash_word| Digest::MD5.hexdigest(hash_word).to_i(16) }.map { |index| index % @filter_size } end def update_index(category, index) oldvalue = @r.getrange(category, index, index) value = 1 value = oldvalue.getbyte(0) + 1 if oldvalue && oldvalue.length > 0 @r.setrange(category_key(category), index, value.chr) end def update_category(category) @r.hincrby(scope_key, category_key(category), 1) end def feature_count(feature, category) # TODO: Add funky caching: tha would keep the calculation code way easier to understand. indexes(feature).map { |index| val = @r.getrange(category_key(category), index, index) val.length > 0 ? val.getbyte(0) : 0 }.min end def total_feature_count feature @categories.inject(0) { |sum, category_array| sum += feature_count(feature, category_array[0]) } end ############################# # Bayes - implementation def p_for_feature_in_category feature, category feature_count(feature, category) / categories[category].to_f end def p_for_feature_in_all_categories feature total_feature_count(feature) / categories_total.to_f end def p_for_feature feature, category p_total = p_for_feature_in_all_categories(feature) p_feature = p_for_feature_in_category(feature, category) ((weight * ap) + (p_total * p_feature)) / (weight + p_total) end def p_for_category features, category ps = features.map { |feature| p_for_feature(feature, category) } p_for_all_features = ps.inject(1.0) { |prod, p| prod *= p } inverse_p_for_all_features = ps.inject(1.0) { |prod, p| prod *= (1.0 - p) } p_for_all_features / (p_for_all_features + inverse_p_for_all_features) end def p_for_all features result = {} @categories.each do |category_array| result[category_array[0]] = p_for_category(features, category_array[0]) end result end def result phrase features = phrase_to_words(phrase) p_for_all(features) end private def scope_key "S:#{scope}" end def category_key category "C:#{category}" end def bloom_key category "B:#{scope}:#{category}" end def phrase_to_words(phrase) phrase.unpack('C*').pack('U*').gsub(/[^\w]/, " ").split.inject([]){|data, w| data << w.downcase}.uniq end end def c bc = Classifier.new 'test' end
module VLC VERSION = "0.0.1.beta" end Version Bump module VLC VERSION = "0.0.1.beta2" end
#-- # Copyright (c) 2010-2011 Engine Yard, Inc. # Copyright (c) 2007-2009 Sun Microsystems, Inc. # This source code is available under the MIT license. # See the file LICENSE.txt for details. #++ require 'ostruct' module Warbler module Traits # The War trait sets up the layout and generates web.xml for the war project. class War include Trait include RakeHelper include PathmapHelper DEFAULT_GEM_PATH = '/WEB-INF/gems' def self.detect? Traits::Rails.detect? || Traits::Merb.detect? || Traits::Rack.detect? end def before_configure config.gem_path = DEFAULT_GEM_PATH config.pathmaps = default_pathmaps config.webxml = default_webxml_config config.webinf_files = default_webinf_files config.java_libs = default_jar_files config.public_html = FileList["public/**/*"] config.jar_extension = 'war' config.init_contents << "#{config.warbler_templates}/war.erb" end def after_configure update_gem_path(DEFAULT_GEM_PATH) end def default_pathmaps p = OpenStruct.new p.public_html = ["%{public/,}p"] p.java_libs = ["WEB-INF/lib/%f"] p.java_classes = ["WEB-INF/classes/%p"] p.application = ["WEB-INF/%p"] p.webinf = ["WEB-INF/%{.erb$,}f"] p.gemspecs = ["#{config.relative_gem_path}/specifications/%f"] p.gems = ["#{config.relative_gem_path}/gems/%p"] p end def default_webxml_config c = WebxmlOpenStruct.new c.public.root = '/' c.jndi = nil c.ignored = %w(jndi booter) c end def default_webinf_files webxml = if File.exist?("config/web.xml") "config/web.xml" elsif File.exist?("config/web.xml.erb") "config/web.xml.erb" else "#{WARBLER_HOME}/web.xml.erb" end FileList[webxml] end def default_jar_files require 'jruby-jars' require 'jruby-rack' FileList[JRubyJars.core_jar_path, JRubyJars.stdlib_jar_path, JRubyJars.jruby_rack_jar_path] end def update_archive(jar) add_public_files(jar) add_webxml(jar) move_jars_to_webinf_lib(jar) add_executables(jar) if config.features.include?("executable") add_gemjar(jar) if config.features.include?("gemjar") end # Add public/static assets to the root of the war file. def add_public_files(jar) config.public_html.exclude *(config.excludes.to_a) config.public_html.map {|f| jar.add_with_pathmaps(config, f, :public_html) } end # Add web.xml and other WEB-INF configuration files from # config.webinf_files to the war file. def add_webxml(jar) config.webinf_files.each do |wf| if wf =~ /\.erb$/ jar.files[apply_pathmaps(config, wf, :webinf)] = jar.expand_erb(wf, config) else jar.files[apply_pathmaps(config, wf, :webinf)] = wf end end end def add_executables(jar) winstone_type = ENV["WINSTONE"] || "winstone-lite" winstone_version = ENV["WINSTONE_VERSION"] || "0.9.10" winstone_path = "net/sourceforge/winstone/#{winstone_type}/#{winstone_version}/#{winstone_type}-#{winstone_version}.jar" winstone_jar = File.expand_path("~/.m2/repository/#{winstone_path}") unless File.exist?(winstone_jar) # Not always covered in tests as these lines may not get # executed every time if the jar is cached. puts "Downloading #{winstone_type}.jar" #:nocov: mkdir_p File.dirname(winstone_jar) #:nocov: require 'open-uri' #:nocov: maven_repo = ENV["MAVEN_REPO"] || "http://repo2.maven.org/maven2" #:nocov: open("#{maven_repo}/#{winstone_path}") do |stream| #:nocov: File.open(winstone_jar, "wb") do |f| #:nocov: while buf = stream.read(4096) #:nocov: f << buf #:nocov: end #:nocov: end #:nocov: end #:nocov: end jar.files['META-INF/MANIFEST.MF'] = StringIO.new(Warbler::Jar::DEFAULT_MANIFEST.chomp + "Main-Class: WarMain\n") jar.files['WarMain.class'] = jar.entry_in_jar("#{WARBLER_HOME}/lib/warbler_jar.jar", 'WarMain.class') jar.files['WEB-INF/winstone.jar'] = winstone_jar end def add_gemjar(jar) gem_jar = Warbler::Jar.new gem_path = Regexp::quote(config.relative_gem_path) gems = jar.files.select{|k,v| k =~ %r{#{gem_path}/} } gems.each do |k,v| gem_jar.files[k.sub(%r{#{gem_path}/}, '')] = v end jar.files["WEB-INF/lib/gems.jar"] = "tmp/gems.jar" jar.files.reject!{|k,v| k =~ /#{gem_path}/ || k == "WEB-INF/tmp/gems.jar"} mkdir_p "tmp" gem_jar.add_manifest gem_jar.create("tmp/gems.jar") end def move_jars_to_webinf_lib(jar) jar.files.keys.select {|k| k =~ /^WEB-INF\/.*\.jar$/ }.each do |k| next if k =~ /^WEB-INF\/lib\/([^\/]+)\.jar$/ # skip jars already in WEB-INF/lib jar.files["WEB-INF/lib/#{k.sub('WEB-INF','')[1..-1].gsub(/[\/\\]/,'-')}"] = jar.files[k] jar.files[k] = empty_jar end end def empty_jar @empty_jar ||= begin t = Tempfile.new(["empty", "jar"]) path = t.path t.unlink Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zipfile| zipfile.mkdir("META-INF") zipfile.get_output_stream("META-INF/MANIFEST.MF") {|f| f << ::Warbler::Jar::DEFAULT_MANIFEST } end at_exit { File.delete(path) } path end end # Helper class for holding arbitrary config.webxml values for injecting into +web.xml+. class WebxmlOpenStruct < OpenStruct object_kernel_methods = (Object.methods + Kernel.methods + Kernel.private_methods) %w(java com org javax gem).each do |name| undef_method name if object_kernel_methods.include?(name) undef_method name.to_sym if object_kernel_methods.include?(name.to_sym) end def initialize(key = 'webxml') @key = key @table = Hash.new {|h,k| h[k] = WebxmlOpenStruct.new(k) } end def servlet_context_listener case self.booter when :rack "org.jruby.rack.RackServletContextListener" when :merb "org.jruby.rack.merb.MerbServletContextListener" else # :rails, default "org.jruby.rack.rails.RailsServletContextListener" end end def [](key) new_ostruct_member(key) send(key) end def []=(key, value) new_ostruct_member(key) send("#{key}=", value) end def context_params(escape = true) require 'cgi' params = {} @table.each do |k,v| case v when WebxmlOpenStruct nested_params = v.context_params nested_params.each do |nk,nv| params["#{escape ? CGI::escapeHTML(k.to_s) : k.to_s}.#{nk}"] = nv end else params[escape ? CGI::escapeHTML(k.to_s) : k.to_s] = escape ? CGI::escapeHTML(v.to_s) : v.to_s end end extra_ignored = Array === ignored ? ignored : [] params.delete_if {|k,v| ['ignored', *extra_ignored].include?(k.to_s) } params end def to_s "No value for '#@key' found" end end end end end Enebo's suggestion in dealing with tempfile paths #-- # Copyright (c) 2010-2011 Engine Yard, Inc. # Copyright (c) 2007-2009 Sun Microsystems, Inc. # This source code is available under the MIT license. # See the file LICENSE.txt for details. #++ require 'ostruct' module Warbler module Traits # The War trait sets up the layout and generates web.xml for the war project. class War include Trait include RakeHelper include PathmapHelper DEFAULT_GEM_PATH = '/WEB-INF/gems' def self.detect? Traits::Rails.detect? || Traits::Merb.detect? || Traits::Rack.detect? end def before_configure config.gem_path = DEFAULT_GEM_PATH config.pathmaps = default_pathmaps config.webxml = default_webxml_config config.webinf_files = default_webinf_files config.java_libs = default_jar_files config.public_html = FileList["public/**/*"] config.jar_extension = 'war' config.init_contents << "#{config.warbler_templates}/war.erb" end def after_configure update_gem_path(DEFAULT_GEM_PATH) end def default_pathmaps p = OpenStruct.new p.public_html = ["%{public/,}p"] p.java_libs = ["WEB-INF/lib/%f"] p.java_classes = ["WEB-INF/classes/%p"] p.application = ["WEB-INF/%p"] p.webinf = ["WEB-INF/%{.erb$,}f"] p.gemspecs = ["#{config.relative_gem_path}/specifications/%f"] p.gems = ["#{config.relative_gem_path}/gems/%p"] p end def default_webxml_config c = WebxmlOpenStruct.new c.public.root = '/' c.jndi = nil c.ignored = %w(jndi booter) c end def default_webinf_files webxml = if File.exist?("config/web.xml") "config/web.xml" elsif File.exist?("config/web.xml.erb") "config/web.xml.erb" else "#{WARBLER_HOME}/web.xml.erb" end FileList[webxml] end def default_jar_files require 'jruby-jars' require 'jruby-rack' FileList[JRubyJars.core_jar_path, JRubyJars.stdlib_jar_path, JRubyJars.jruby_rack_jar_path] end def update_archive(jar) add_public_files(jar) add_webxml(jar) move_jars_to_webinf_lib(jar) add_executables(jar) if config.features.include?("executable") add_gemjar(jar) if config.features.include?("gemjar") end # Add public/static assets to the root of the war file. def add_public_files(jar) config.public_html.exclude *(config.excludes.to_a) config.public_html.map {|f| jar.add_with_pathmaps(config, f, :public_html) } end # Add web.xml and other WEB-INF configuration files from # config.webinf_files to the war file. def add_webxml(jar) config.webinf_files.each do |wf| if wf =~ /\.erb$/ jar.files[apply_pathmaps(config, wf, :webinf)] = jar.expand_erb(wf, config) else jar.files[apply_pathmaps(config, wf, :webinf)] = wf end end end def add_executables(jar) winstone_type = ENV["WINSTONE"] || "winstone-lite" winstone_version = ENV["WINSTONE_VERSION"] || "0.9.10" winstone_path = "net/sourceforge/winstone/#{winstone_type}/#{winstone_version}/#{winstone_type}-#{winstone_version}.jar" winstone_jar = File.expand_path("~/.m2/repository/#{winstone_path}") unless File.exist?(winstone_jar) # Not always covered in tests as these lines may not get # executed every time if the jar is cached. puts "Downloading #{winstone_type}.jar" #:nocov: mkdir_p File.dirname(winstone_jar) #:nocov: require 'open-uri' #:nocov: maven_repo = ENV["MAVEN_REPO"] || "http://repo2.maven.org/maven2" #:nocov: open("#{maven_repo}/#{winstone_path}") do |stream| #:nocov: File.open(winstone_jar, "wb") do |f| #:nocov: while buf = stream.read(4096) #:nocov: f << buf #:nocov: end #:nocov: end #:nocov: end #:nocov: end jar.files['META-INF/MANIFEST.MF'] = StringIO.new(Warbler::Jar::DEFAULT_MANIFEST.chomp + "Main-Class: WarMain\n") jar.files['WarMain.class'] = jar.entry_in_jar("#{WARBLER_HOME}/lib/warbler_jar.jar", 'WarMain.class') jar.files['WEB-INF/winstone.jar'] = winstone_jar end def add_gemjar(jar) gem_jar = Warbler::Jar.new gem_path = Regexp::quote(config.relative_gem_path) gems = jar.files.select{|k,v| k =~ %r{#{gem_path}/} } gems.each do |k,v| gem_jar.files[k.sub(%r{#{gem_path}/}, '')] = v end jar.files["WEB-INF/lib/gems.jar"] = "tmp/gems.jar" jar.files.reject!{|k,v| k =~ /#{gem_path}/ || k == "WEB-INF/tmp/gems.jar"} mkdir_p "tmp" gem_jar.add_manifest gem_jar.create("tmp/gems.jar") end def move_jars_to_webinf_lib(jar) jar.files.keys.select {|k| k =~ /^WEB-INF\/.*\.jar$/ }.each do |k| next if k =~ /^WEB-INF\/lib\/([^\/]+)\.jar$/ # skip jars already in WEB-INF/lib jar.files["WEB-INF/lib/#{k.sub('WEB-INF','')[1..-1].gsub(/[\/\\]/,'-')}"] = jar.files[k] jar.files[k] = empty_jar end end def empty_jar @empty_jar ||= begin path = Tempfile.open(["empty", "jar"]) {|t| return t.path } Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |zipfile| zipfile.mkdir("META-INF") zipfile.get_output_stream("META-INF/MANIFEST.MF") {|f| f << ::Warbler::Jar::DEFAULT_MANIFEST } end at_exit { File.delete(path) } path end end # Helper class for holding arbitrary config.webxml values for injecting into +web.xml+. class WebxmlOpenStruct < OpenStruct object_kernel_methods = (Object.methods + Kernel.methods + Kernel.private_methods) %w(java com org javax gem).each do |name| undef_method name if object_kernel_methods.include?(name) undef_method name.to_sym if object_kernel_methods.include?(name.to_sym) end def initialize(key = 'webxml') @key = key @table = Hash.new {|h,k| h[k] = WebxmlOpenStruct.new(k) } end def servlet_context_listener case self.booter when :rack "org.jruby.rack.RackServletContextListener" when :merb "org.jruby.rack.merb.MerbServletContextListener" else # :rails, default "org.jruby.rack.rails.RailsServletContextListener" end end def [](key) new_ostruct_member(key) send(key) end def []=(key, value) new_ostruct_member(key) send("#{key}=", value) end def context_params(escape = true) require 'cgi' params = {} @table.each do |k,v| case v when WebxmlOpenStruct nested_params = v.context_params nested_params.each do |nk,nv| params["#{escape ? CGI::escapeHTML(k.to_s) : k.to_s}.#{nk}"] = nv end else params[escape ? CGI::escapeHTML(k.to_s) : k.to_s] = escape ? CGI::escapeHTML(v.to_s) : v.to_s end end extra_ignored = Array === ignored ? ignored : [] params.delete_if {|k,v| ['ignored', *extra_ignored].include?(k.to_s) } params end def to_s "No value for '#@key' found" end end end end end
require 'fastlane_core' require 'credentials_manager' module WatchBuild class Options def self.available_options [ FastlaneCore::ConfigItem.new(key: :app_identifier, short_option: "-a", env_name: "APP_IDENTIFIER", description: "The bundle identifier of your app", default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier)), FastlaneCore::ConfigItem.new(key: :username, short_option: "-u", env_name: "FASTLANE_USER", description: "Your Apple ID Username", default_value: CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)) ] end end end Added support for itc specific username require 'fastlane_core' require 'credentials_manager' module WatchBuild class Options def self.available_options user = CredentialsManager::AppfileConfig.try_fetch_value(:itunes_connect_id) user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id) [ FastlaneCore::ConfigItem.new(key: :app_identifier, short_option: "-a", env_name: "APP_IDENTIFIER", description: "The bundle identifier of your app", default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier)), FastlaneCore::ConfigItem.new(key: :username, short_option: "-u", env_name: "FASTLANE_USER", description: "Your Apple ID Username", default_value: user) ] end end end
module Bendy module Shape def shape(*args) if args[0].kind_of?(Hash) klass = Class.new attributes = args[0] else klass, attributes = args end attributes.each do |attribute, value| if value.kind_of?(Proc) klass.send(:define_method, attribute, &value) else klass.send(:define_method, attribute) do value end end end klass.new end end end Optimillisize the shape implementation. module Bendy module Shape def shape(*args) klass = args[0].kind_of?(Hash) ? Class.new : args.shift attributes = args[0] attributes.each do |attribute, value| proc = value.kind_of?(Proc) ? value : lambda { value } klass.send(:define_method, attribute, &proc) end klass.new end end end
class Flow def initialize(jurisdiction, type) path = get_path(jurisdiction, type) @xml = Nokogiri::XML(File.open(path)) @xml_copy = Nokogiri::XML(File.open(path)) end def get_path(jurisdiction, type) jurisdiction = "en" if (jurisdiction == "gb" && type == "Practical") jurisdiction.upcase! if type == "Legal" folder = folder_name(type) path = File.join(Rails.root, 'prototype', folder, "certificate.#{jurisdiction}.xml") unless File.exist?(path) path = File.join(Rails.root, 'prototype', folder, "certificate.en.xml") end path end def folder_name(type) { "Legal" => "jurisdictions", "Practical" => "translations" }[type] end def questions @xml_copy.xpath("//if").remove # remove any dependencies @xml_copy.xpath("//question").map do |q| question(q) end end def dependencies @xml.xpath("//if//question").map do |q| question(q, true) end end def question(q, dependency = true) { id: q["id"], label: label(q), type: type(q), level: level(q), answers: answers(q), prerequisites: dependency === true ? prerequisites(q) : nil } end def answers(question) if type(question) == "yesno" { "true" => { dependency: dependency(question, "true") }, "false" => { dependency: dependency(question, "false") } } elsif question.at_xpath("radioset|checkboxset") answers = {} question.at_xpath("radioset|checkboxset").xpath("option").each do |option| answers[option.at_xpath("label").text] = { dependency: dependency(question, option["value"]) } end answers elsif question.at_xpath("select") answers = {} question.at_xpath("select").xpath("option").each do |option| next if option["value"].nil? answers[option["value"]] = { dependency: dependency(question, option["value"]) } end answers end end def label(question) CGI.unescapeHTML(question.at_xpath("label").text).gsub("\"", "'") end def type(question) if question.at_xpath("input") "input" elsif question.at_xpath("yesno") "yesno" elsif question.at_xpath("radioset") "radioset" elsif question.at_xpath("checkboxset") "checkboxset" end end def level(question) question.at_xpath("requirement")["level"] unless question.at_xpath("requirement").nil? end def dependency(question, answer) dependency = @xml.xpath("//if[contains(@test, \"this.#{question["id"]}() === '#{answer}'\")]").at_css("question") dependency["id"] unless dependency.nil? end def prerequisites(question) test = question.parent["test"] || question.parent.parent["test"] test.scan(/this\.([a-z]+)\(\)/i).map { |s| s[0] } unless test.nil? end end Use license text, rather than IDs class Flow def initialize(jurisdiction, type) path = get_path(jurisdiction, type) @xml = Nokogiri::XML(File.open(path)) @xml_copy = Nokogiri::XML(File.open(path)) end def get_path(jurisdiction, type) jurisdiction = "en" if (jurisdiction == "gb" && type == "Practical") jurisdiction.upcase! if type == "Legal" folder = folder_name(type) path = File.join(Rails.root, 'prototype', folder, "certificate.#{jurisdiction}.xml") unless File.exist?(path) path = File.join(Rails.root, 'prototype', folder, "certificate.en.xml") end path end def folder_name(type) { "Legal" => "jurisdictions", "Practical" => "translations" }[type] end def questions @xml_copy.xpath("//if").remove # remove any dependencies @xml_copy.xpath("//question").map do |q| question(q) end end def dependencies @xml.xpath("//if//question").map do |q| question(q, true) end end def question(q, dependency = true) { id: q["id"], label: label(q), type: type(q), level: level(q), answers: answers(q), prerequisites: dependency === true ? prerequisites(q) : nil } end def answers(question) if type(question) == "yesno" { "true" => { dependency: dependency(question, "true") }, "false" => { dependency: dependency(question, "false") } } elsif question.at_xpath("radioset|checkboxset") answers = {} question.at_xpath("radioset|checkboxset").xpath("option").each do |option| answers[option.at_xpath("label").text] = { dependency: dependency(question, option["value"]) } end answers elsif question.at_xpath("select") answers = {} question.at_xpath("select").xpath("option").each do |option| next if option["value"].nil? answers[option.text] = { dependency: dependency(question, option["value"]) } end answers end end def label(question) CGI.unescapeHTML(question.at_xpath("label").text).gsub("\"", "'") end def type(question) if question.at_xpath("input") "input" elsif question.at_xpath("yesno") "yesno" elsif question.at_xpath("radioset") "radioset" elsif question.at_xpath("checkboxset") "checkboxset" end end def level(question) question.at_xpath("requirement")["level"] unless question.at_xpath("requirement").nil? end def dependency(question, answer) dependency = @xml.xpath("//if[contains(@test, \"this.#{question["id"]}() === '#{answer}'\")]").at_css("question") dependency["id"] unless dependency.nil? end def prerequisites(question) test = question.parent["test"] || question.parent.parent["test"] test.scan(/this\.([a-z]+)\(\)/i).map { |s| s[0] } unless test.nil? end end