id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
14,600
simukappu/activity_notification
lib/activity_notification/helpers/view_helpers.rb
ActivityNotification.ViewHelpers.subscribe_subscription_url_for
def subscribe_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("subscribe_#{routing_scope(options)}subscription_url", subscription, options) : send("subscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
ruby
def subscribe_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("subscribe_#{routing_scope(options)}subscription_url", subscription, options) : send("subscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
[ "def", "subscribe_subscription_url_for", "(", "subscription", ",", "params", "=", "{", "}", ")", "options", "=", "params", ".", "dup", "options", ".", "delete", "(", ":devise_default_routes", ")", "?", "send", "(", "\"subscribe_#{routing_scope(options)}subscription_url\"", ",", "subscription", ",", "options", ")", ":", "send", "(", "\"subscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url\"", ",", "subscription", ".", "target", ",", "subscription", ",", "options", ")", "end" ]
Returns subscribe_subscription_url for the target of specified subscription @param [Subscription] subscription Subscription instance @param [Hash] params Request parameters @return [String] subscription_url for the subscription @todo Needs any other better implementation
[ "Returns", "subscribe_subscription_url", "for", "the", "target", "of", "specified", "subscription" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/helpers/view_helpers.rb#L356-L361
14,601
simukappu/activity_notification
lib/activity_notification/helpers/view_helpers.rb
ActivityNotification.ViewHelpers.unsubscribe_subscription_url_for
def unsubscribe_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("unsubscribe_#{routing_scope(options)}subscription_url", subscription, options) : send("unsubscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
ruby
def unsubscribe_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("unsubscribe_#{routing_scope(options)}subscription_url", subscription, options) : send("unsubscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
[ "def", "unsubscribe_subscription_url_for", "(", "subscription", ",", "params", "=", "{", "}", ")", "options", "=", "params", ".", "dup", "options", ".", "delete", "(", ":devise_default_routes", ")", "?", "send", "(", "\"unsubscribe_#{routing_scope(options)}subscription_url\"", ",", "subscription", ",", "options", ")", ":", "send", "(", "\"unsubscribe_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url\"", ",", "subscription", ".", "target", ",", "subscription", ",", "options", ")", "end" ]
Returns unsubscribe_subscription_url for the target of specified subscription @param [Subscription] subscription Subscription instance @param [Hash] params Request parameters @return [String] subscription_url for the subscription @todo Needs any other better implementation
[ "Returns", "unsubscribe_subscription_url", "for", "the", "target", "of", "specified", "subscription" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/helpers/view_helpers.rb#L370-L375
14,602
simukappu/activity_notification
lib/activity_notification/helpers/view_helpers.rb
ActivityNotification.ViewHelpers.subscribe_to_email_subscription_url_for
def subscribe_to_email_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("subscribe_to_email_#{routing_scope(options)}subscription_url", subscription, options) : send("subscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
ruby
def subscribe_to_email_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("subscribe_to_email_#{routing_scope(options)}subscription_url", subscription, options) : send("subscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
[ "def", "subscribe_to_email_subscription_url_for", "(", "subscription", ",", "params", "=", "{", "}", ")", "options", "=", "params", ".", "dup", "options", ".", "delete", "(", ":devise_default_routes", ")", "?", "send", "(", "\"subscribe_to_email_#{routing_scope(options)}subscription_url\"", ",", "subscription", ",", "options", ")", ":", "send", "(", "\"subscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url\"", ",", "subscription", ".", "target", ",", "subscription", ",", "options", ")", "end" ]
Returns subscribe_to_email_subscription_url for the target of specified subscription @param [Subscription] subscription Subscription instance @param [Hash] params Request parameters @return [String] subscription_url for the subscription @todo Needs any other better implementation
[ "Returns", "subscribe_to_email_subscription_url", "for", "the", "target", "of", "specified", "subscription" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/helpers/view_helpers.rb#L384-L389
14,603
simukappu/activity_notification
lib/activity_notification/helpers/view_helpers.rb
ActivityNotification.ViewHelpers.unsubscribe_to_email_subscription_url_for
def unsubscribe_to_email_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("unsubscribe_to_email_#{routing_scope(options)}subscription_url", subscription, options) : send("unsubscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
ruby
def unsubscribe_to_email_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("unsubscribe_to_email_#{routing_scope(options)}subscription_url", subscription, options) : send("unsubscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
[ "def", "unsubscribe_to_email_subscription_url_for", "(", "subscription", ",", "params", "=", "{", "}", ")", "options", "=", "params", ".", "dup", "options", ".", "delete", "(", ":devise_default_routes", ")", "?", "send", "(", "\"unsubscribe_to_email_#{routing_scope(options)}subscription_url\"", ",", "subscription", ",", "options", ")", ":", "send", "(", "\"unsubscribe_to_email_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url\"", ",", "subscription", ".", "target", ",", "subscription", ",", "options", ")", "end" ]
Returns unsubscribe_to_email_subscription_url for the target of specified subscription @param [Subscription] subscription Subscription instance @param [Hash] params Request parameters @return [String] subscription_url for the subscription @todo Needs any other better implementation
[ "Returns", "unsubscribe_to_email_subscription_url", "for", "the", "target", "of", "specified", "subscription" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/helpers/view_helpers.rb#L398-L403
14,604
simukappu/activity_notification
lib/activity_notification/helpers/view_helpers.rb
ActivityNotification.ViewHelpers.subscribe_to_optional_target_subscription_url_for
def subscribe_to_optional_target_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("subscribe_to_optional_target_#{routing_scope(options)}subscription_url", subscription, options) : send("subscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
ruby
def subscribe_to_optional_target_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("subscribe_to_optional_target_#{routing_scope(options)}subscription_url", subscription, options) : send("subscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
[ "def", "subscribe_to_optional_target_subscription_url_for", "(", "subscription", ",", "params", "=", "{", "}", ")", "options", "=", "params", ".", "dup", "options", ".", "delete", "(", ":devise_default_routes", ")", "?", "send", "(", "\"subscribe_to_optional_target_#{routing_scope(options)}subscription_url\"", ",", "subscription", ",", "options", ")", ":", "send", "(", "\"subscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url\"", ",", "subscription", ".", "target", ",", "subscription", ",", "options", ")", "end" ]
Returns subscribe_to_optional_target_subscription_url for the target of specified subscription @param [Subscription] subscription Subscription instance @param [Hash] params Request parameters @return [String] subscription_url for the subscription @todo Needs any other better implementation
[ "Returns", "subscribe_to_optional_target_subscription_url", "for", "the", "target", "of", "specified", "subscription" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/helpers/view_helpers.rb#L412-L417
14,605
simukappu/activity_notification
lib/activity_notification/helpers/view_helpers.rb
ActivityNotification.ViewHelpers.unsubscribe_to_optional_target_subscription_url_for
def unsubscribe_to_optional_target_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("unsubscribe_to_optional_target_#{routing_scope(options)}subscription_url", subscription, options) : send("unsubscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
ruby
def unsubscribe_to_optional_target_subscription_url_for(subscription, params = {}) options = params.dup options.delete(:devise_default_routes) ? send("unsubscribe_to_optional_target_#{routing_scope(options)}subscription_url", subscription, options) : send("unsubscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url", subscription.target, subscription, options) end
[ "def", "unsubscribe_to_optional_target_subscription_url_for", "(", "subscription", ",", "params", "=", "{", "}", ")", "options", "=", "params", ".", "dup", "options", ".", "delete", "(", ":devise_default_routes", ")", "?", "send", "(", "\"unsubscribe_to_optional_target_#{routing_scope(options)}subscription_url\"", ",", "subscription", ",", "options", ")", ":", "send", "(", "\"unsubscribe_to_optional_target_#{routing_scope(options)}#{subscription.target.to_resource_name}_subscription_url\"", ",", "subscription", ".", "target", ",", "subscription", ",", "options", ")", "end" ]
Returns unsubscribe_to_optional_target_subscription_url for the target of specified subscription @param [Subscription] subscription Subscription instance @param [Hash] params Request parameters @return [String] subscription_url for the subscription @todo Needs any other better implementation
[ "Returns", "unsubscribe_to_optional_target_subscription_url", "for", "the", "target", "of", "specified", "subscription" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/helpers/view_helpers.rb#L426-L431
14,606
simukappu/activity_notification
lib/activity_notification/controllers/common_controller.rb
ActivityNotification.CommonController.target_view_path
def target_view_path target_type = @target.to_resources_name view_path = [controller_path, target_type].join('/') lookup_context.exists?(action_name, view_path) ? view_path : [controller_path, DEFAULT_VIEW_DIRECTORY].join('/') end
ruby
def target_view_path target_type = @target.to_resources_name view_path = [controller_path, target_type].join('/') lookup_context.exists?(action_name, view_path) ? view_path : [controller_path, DEFAULT_VIEW_DIRECTORY].join('/') end
[ "def", "target_view_path", "target_type", "=", "@target", ".", "to_resources_name", "view_path", "=", "[", "controller_path", ",", "target_type", "]", ".", "join", "(", "'/'", ")", "lookup_context", ".", "exists?", "(", "action_name", ",", "view_path", ")", "?", "view_path", ":", "[", "controller_path", ",", "DEFAULT_VIEW_DIRECTORY", "]", ".", "join", "(", "'/'", ")", "end" ]
Returns path of the target view templates. Do not make this method public unless Rendarable module calls controller's target_view_path method to render resources. @api protected
[ "Returns", "path", "of", "the", "target", "view", "templates", ".", "Do", "not", "make", "this", "method", "public", "unless", "Rendarable", "module", "calls", "controller", "s", "target_view_path", "method", "to", "render", "resources", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/controllers/common_controller.rb#L71-L77
14,607
simukappu/activity_notification
lib/activity_notification/controllers/common_controller.rb
ActivityNotification.CommonController.return_back_or_ajax
def return_back_or_ajax set_index_options respond_to do |format| if request.xhr? load_index if params[:reload].to_s.to_boolean(true) format.js else compatibly_redirect_back(@index_options) and return end end end
ruby
def return_back_or_ajax set_index_options respond_to do |format| if request.xhr? load_index if params[:reload].to_s.to_boolean(true) format.js else compatibly_redirect_back(@index_options) and return end end end
[ "def", "return_back_or_ajax", "set_index_options", "respond_to", "do", "|", "format", "|", "if", "request", ".", "xhr?", "load_index", "if", "params", "[", ":reload", "]", ".", "to_s", ".", "to_boolean", "(", "true", ")", "format", ".", "js", "else", "compatibly_redirect_back", "(", "@index_options", ")", "and", "return", "end", "end", "end" ]
Returns JavaScript view for ajax request or redirects to back as default. @api protected @return [Responce] JavaScript view for ajax request or redirects to back as default
[ "Returns", "JavaScript", "view", "for", "ajax", "request", "or", "redirects", "to", "back", "as", "default", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/controllers/common_controller.rb#L88-L98
14,608
simukappu/activity_notification
lib/activity_notification/controllers/common_controller.rb
ActivityNotification.CommonController.compatibly_redirect_back
def compatibly_redirect_back(request_params = {}) # :only-rails5+: if Rails::VERSION::MAJOR >= 5 redirect_back fallback_location: { action: :index }, **request_params # :only-rails5+: # :except-rails5+: elsif request.referer redirect_to :back, **request_params else redirect_to action: :index, **request_params end # :except-rails5+: true end
ruby
def compatibly_redirect_back(request_params = {}) # :only-rails5+: if Rails::VERSION::MAJOR >= 5 redirect_back fallback_location: { action: :index }, **request_params # :only-rails5+: # :except-rails5+: elsif request.referer redirect_to :back, **request_params else redirect_to action: :index, **request_params end # :except-rails5+: true end
[ "def", "compatibly_redirect_back", "(", "request_params", "=", "{", "}", ")", "# :only-rails5+:", "if", "Rails", "::", "VERSION", "::", "MAJOR", ">=", "5", "redirect_back", "fallback_location", ":", "{", "action", ":", ":index", "}", ",", "**", "request_params", "# :only-rails5+:", "# :except-rails5+:", "elsif", "request", ".", "referer", "redirect_to", ":back", ",", "**", "request_params", "else", "redirect_to", "action", ":", ":index", ",", "**", "request_params", "end", "# :except-rails5+:", "true", "end" ]
Redirect to back. @api protected @return [Boolean] True
[ "Redirect", "to", "back", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/controllers/common_controller.rb#L103-L116
14,609
simukappu/activity_notification
lib/activity_notification/rails/routes.rb
ActionDispatch::Routing.Mapper.notify_to
def notify_to(*resources) options = create_options(:notifications, resources.extract_options!, [:new, :create, :edit, :update]) resources.each do |target| options[:defaults] = { target_type: target.to_s }.merge(options[:devise_defaults]) resources_options = options.select { |key, _| [:with_devise, :devise_default_routes, :with_subscription, :subscription_option, :model, :devise_defaults].exclude? key } if options[:with_devise].present? && options[:devise_default_routes].present? create_notification_routes options, resources_options else self.resources target, only: :none do create_notification_routes options, resources_options end end if options[:with_subscription].present? && target.to_s.to_model_class.subscription_enabled? subscribed_by target, options[:subscription_option] end end self end
ruby
def notify_to(*resources) options = create_options(:notifications, resources.extract_options!, [:new, :create, :edit, :update]) resources.each do |target| options[:defaults] = { target_type: target.to_s }.merge(options[:devise_defaults]) resources_options = options.select { |key, _| [:with_devise, :devise_default_routes, :with_subscription, :subscription_option, :model, :devise_defaults].exclude? key } if options[:with_devise].present? && options[:devise_default_routes].present? create_notification_routes options, resources_options else self.resources target, only: :none do create_notification_routes options, resources_options end end if options[:with_subscription].present? && target.to_s.to_model_class.subscription_enabled? subscribed_by target, options[:subscription_option] end end self end
[ "def", "notify_to", "(", "*", "resources", ")", "options", "=", "create_options", "(", ":notifications", ",", "resources", ".", "extract_options!", ",", "[", ":new", ",", ":create", ",", ":edit", ",", ":update", "]", ")", "resources", ".", "each", "do", "|", "target", "|", "options", "[", ":defaults", "]", "=", "{", "target_type", ":", "target", ".", "to_s", "}", ".", "merge", "(", "options", "[", ":devise_defaults", "]", ")", "resources_options", "=", "options", ".", "select", "{", "|", "key", ",", "_", "|", "[", ":with_devise", ",", ":devise_default_routes", ",", ":with_subscription", ",", ":subscription_option", ",", ":model", ",", ":devise_defaults", "]", ".", "exclude?", "key", "}", "if", "options", "[", ":with_devise", "]", ".", "present?", "&&", "options", "[", ":devise_default_routes", "]", ".", "present?", "create_notification_routes", "options", ",", "resources_options", "else", "self", ".", "resources", "target", ",", "only", ":", ":none", "do", "create_notification_routes", "options", ",", "resources_options", "end", "end", "if", "options", "[", ":with_subscription", "]", ".", "present?", "&&", "target", ".", "to_s", ".", "to_model_class", ".", "subscription_enabled?", "subscribed_by", "target", ",", "options", "[", ":subscription_option", "]", "end", "end", "self", "end" ]
Includes notify_to method for routes, which is responsible to generate all necessary routes for notifications of activity_notification. When you have an User model configured as a target (e.g. defined acts_as_target), you can create as follows in your routes: notify_to :users This method creates the needed routes: # Notification routes user_notifications GET /users/:user_id/notifications(.:format) { controller:"activity_notification/notifications", action:"index", target_type:"users" } user_notification GET /users/:user_id/notifications/:id(.:format) { controller:"activity_notification/notifications", action:"show", target_type:"users" } user_notification DELETE /users/:user_id/notifications/:id(.:format) { controller:"activity_notification/notifications", action:"destroy", target_type:"users" } open_all_user_notifications POST /users/:user_id/notifications/open_all(.:format) { controller:"activity_notification/notifications", action:"open_all", target_type:"users" } move_user_notification GET /users/:user_id/notifications/:id/move(.:format) { controller:"activity_notification/notifications", action:"move", target_type:"users" } open_user_notification POST /users/:user_id/notifications/:id/open(.:format) { controller:"activity_notification/notifications", action:"open", target_type:"users" } You can also configure notification routes with scope like this: scope :myscope, as: :myscope do notify_to :users, routing_scope: :myscope end This routing_scope option creates the needed routes with specified scope like this: # Notification routes myscope_user_notifications GET /myscope/users/:user_id/notifications(.:format) { controller:"activity_notification/notifications", action:"index", target_type:"users", routing_scope: :myscope } myscope_user_notification GET /myscope/users/:user_id/notifications/:id(.:format) { controller:"activity_notification/notifications", action:"show", target_type:"users", routing_scope: :myscope } myscope_user_notification DELETE /myscope/users/:user_id/notifications/:id(.:format) { controller:"activity_notification/notifications", action:"destroy", target_type:"users", routing_scope: :myscope } open_all_myscope_user_notifications POST /myscope/users/:user_id/notifications/open_all(.:format) { controller:"activity_notification/notifications", action:"open_all", target_type:"users", routing_scope: :myscope } move_myscope_user_notification GET /myscope/users/:user_id/notifications/:id/move(.:format) { controller:"activity_notification/notifications", action:"move", target_type:"users", routing_scope: :myscope } open_myscope_user_notification POST /myscope/users/:user_id/notifications/:id/open(.:format) { controller:"activity_notification/notifications", action:"open", target_type:"users", routing_scope: :myscope } When you use devise authentication and you want make notification targets assciated with devise, you can create as follows in your routes: notify_to :users, with_devise: :users This with_devise option creates the needed routes assciated with devise authentication: # Notification with devise routes user_notifications GET /users/:user_id/notifications(.:format) { controller:"activity_notification/notifications_with_devise", action:"index", target_type:"users", devise_type:"users" } user_notification GET /users/:user_id/notifications/:id(.:format) { controller:"activity_notification/notifications_with_devise", action:"show", target_type:"users", devise_type:"users" } user_notification DELETE /users/:user_id/notifications/:id(.:format) { controller:"activity_notification/notifications_with_devise", action:"destroy", target_type:"users", devise_type:"users" } open_all_user_notifications POST /users/:user_id/notifications/open_all(.:format) { controller:"activity_notification/notifications_with_devise", action:"open_all", target_type:"users", devise_type:"users" } move_user_notification GET /users/:user_id/notifications/:id/move(.:format) { controller:"activity_notification/notifications_with_devise", action:"move", target_type:"users", devise_type:"users" } open_user_notification POST /users/:user_id/notifications/:id/open(.:format) { controller:"activity_notification/notifications_with_devise", action:"open", target_type:"users", devise_type:"users" } When you use with_devise option and you want to make simple default routes as follows, you can use devise_default_routes option: notify_to :users, with_devise: :users, devise_default_routes: true These with_devise and devise_default_routes options create the needed routes assciated with authenticated devise resource as the default target # Notification with default devise routes user_notifications GET /notifications(.:format) { controller:"activity_notification/notifications_with_devise", action:"index", target_type:"users", devise_type:"users" } user_notification GET /notifications/:id(.:format) { controller:"activity_notification/notifications_with_devise", action:"show", target_type:"users", devise_type:"users" } user_notification DELETE /notifications/:id(.:format) { controller:"activity_notification/notifications_with_devise", action:"destroy", target_type:"users", devise_type:"users" } open_all_user_notifications POST /notifications/open_all(.:format) { controller:"activity_notification/notifications_with_devise", action:"open_all", target_type:"users", devise_type:"users" } move_user_notification GET /notifications/:id/move(.:format) { controller:"activity_notification/notifications_with_devise", action:"move", target_type:"users", devise_type:"users" } open_user_notification POST /notifications/:id/open(.:format) { controller:"activity_notification/notifications_with_devise", action:"open", target_type:"users", devise_type:"users" } When you would like to define subscription management paths with notification paths, you can create as follows in your routes: notify_to :users, with_subscription: true or you can also set options for subscription path: notify_to :users, with_subscription: { except: [:index] } If you configure this :with_subscription option with :with_devise option, with_subscription paths are also automatically configured with devise authentication as the same as notifications notify_to :users, with_devise: :users, with_subscription: true @example Define notify_to in config/routes.rb notify_to :users @example Define notify_to with options notify_to :users, only: [:open, :open_all, :move] @example Integrated with Devise authentication notify_to :users, with_devise: :users @example Define notification paths including subscription paths notify_to :users, with_subscription: true @example Integrated with Devise authentication as simple default routes including subscription management notify_to :users, with_devise: :users, devise_default_routes: true, with_subscription: true @example Integrated with Devise authentication as simple default routes with scope including subscription management scope :myscope, as: :myscope do notify_to :myscope, with_devise: :users, devise_default_routes: true, with_subscription: true, routing_scope: :myscope end @overload notify_to(*resources, *options) @param [Symbol] resources Resources to notify @option options [String] :routing_scope (nil) Routing scope for notification routes @option options [Symbol] :with_devise (false) Devise resources name for devise integration. Devise integration will be enabled by this option. @option options [Boolean] :devise_default_routes (false) Whether you will create routes as device default routes assciated with authenticated devise resource as the default target @option options [Hash|Boolean] :with_subscription (false) Subscription path options to define subscription management paths with notification paths. Calls subscribed_by routing when truthy value is passed as this option. @option options [String] :model (:notifications) Model name of notifications @option options [String] :controller ("activity_notification/notifications" | activity_notification/notifications_with_devise") :controller option as resources routing @option options [Symbol] :as (nil) :as option as resources routing @option options [Array] :only (nil) :only option as resources routing @option options [Array] :except (nil) :except option as resources routing @return [ActionDispatch::Routing::Mapper] Routing mapper instance
[ "Includes", "notify_to", "method", "for", "routes", "which", "is", "responsible", "to", "generate", "all", "necessary", "routes", "for", "notifications", "of", "activity_notification", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/rails/routes.rb#L118-L138
14,610
simukappu/activity_notification
lib/activity_notification/rails/routes.rb
ActionDispatch::Routing.Mapper.subscribed_by
def subscribed_by(*resources) options = create_options(:subscriptions, resources.extract_options!, [:new, :edit, :update]) resources.each do |target| options[:defaults] = { target_type: target.to_s }.merge(options[:devise_defaults]) resources_options = options.select { |key, _| [:with_devise, :devise_default_routes, :model, :devise_defaults].exclude? key } if options[:with_devise].present? && options[:devise_default_routes].present? create_subscription_routes options, resources_options else self.resources target, only: :none do create_subscription_routes options, resources_options end end end self end
ruby
def subscribed_by(*resources) options = create_options(:subscriptions, resources.extract_options!, [:new, :edit, :update]) resources.each do |target| options[:defaults] = { target_type: target.to_s }.merge(options[:devise_defaults]) resources_options = options.select { |key, _| [:with_devise, :devise_default_routes, :model, :devise_defaults].exclude? key } if options[:with_devise].present? && options[:devise_default_routes].present? create_subscription_routes options, resources_options else self.resources target, only: :none do create_subscription_routes options, resources_options end end end self end
[ "def", "subscribed_by", "(", "*", "resources", ")", "options", "=", "create_options", "(", ":subscriptions", ",", "resources", ".", "extract_options!", ",", "[", ":new", ",", ":edit", ",", ":update", "]", ")", "resources", ".", "each", "do", "|", "target", "|", "options", "[", ":defaults", "]", "=", "{", "target_type", ":", "target", ".", "to_s", "}", ".", "merge", "(", "options", "[", ":devise_defaults", "]", ")", "resources_options", "=", "options", ".", "select", "{", "|", "key", ",", "_", "|", "[", ":with_devise", ",", ":devise_default_routes", ",", ":model", ",", ":devise_defaults", "]", ".", "exclude?", "key", "}", "if", "options", "[", ":with_devise", "]", ".", "present?", "&&", "options", "[", ":devise_default_routes", "]", ".", "present?", "create_subscription_routes", "options", ",", "resources_options", "else", "self", ".", "resources", "target", ",", "only", ":", ":none", "do", "create_subscription_routes", "options", ",", "resources_options", "end", "end", "end", "self", "end" ]
Includes subscribed_by method for routes, which is responsible to generate all necessary routes for subscriptions of activity_notification. When you have an User model configured as a target (e.g. defined acts_as_target), you can create as follows in your routes: subscribed_by :users This method creates the needed routes: # Subscription routes user_subscriptions GET /users/:user_id/subscriptions(.:format) { controller:"activity_notification/subscriptions", action:"index", target_type:"users" } user_subscription GET /users/:user_id/subscriptions/:id(.:format) { controller:"activity_notification/subscriptions", action:"show", target_type:"users" } open_all_user_subscriptions POST /users/:user_id/subscriptions(.:format) { controller:"activity_notification/subscriptions", action:"create", target_type:"users" } user_subscription DELETE /users/:user_id/subscriptions/:id(.:format) { controller:"activity_notification/subscriptions", action:"destroy", target_type:"users" } subscribe_user_subscription POST /users/:user_id/subscriptions/:id/subscribe(.:format) { controller:"activity_notification/subscriptions", action:"subscribe", target_type:"users" } unsubscribe_user_subscription POST /users/:user_id/subscriptions/:id/unsubscribe(.:format) { controller:"activity_notification/subscriptions", action:"unsubscribe", target_type:"users" } subscribe_to_email_user_subscription POST /users/:user_id/subscriptions/:id/subscribe_to_email(.:format) { controller:"activity_notification/subscriptions", action:"subscribe_to_email", target_type:"users" } unsubscribe_to_email_user_subscription POST /users/:user_id/subscriptions/:id/unsubscribe_to_email(.:format) { controller:"activity_notification/subscriptions", action:"unsubscribe_to_email", target_type:"users" } subscribe_to_optional_target_user_subscription POST /users/:user_id/subscriptions/:id/subscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions", action:"subscribe_to_optional_target", target_type:"users" } unsubscribe_to_optional_target_user_subscription POST /users/:user_id/subscriptions/:id/unsubscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions", action:"unsubscribe_to_optional_target", target_type:"users" } You can also configure notification routes with scope like this: scope :myscope, as: :myscope do subscribed_by :users, routing_scope: :myscope end This routing_scope option creates the needed routes with specified scope like this: # Subscription routes myscope_user_subscriptions GET /myscope/users/:user_id/subscriptions(.:format) { controller:"activity_notification/subscriptions", action:"index", target_type:"users", routing_scope: :myscope } myscope_user_subscription GET /myscope/users/:user_id/subscriptions/:id(.:format) { controller:"activity_notification/subscriptions", action:"show", target_type:"users", routing_scope: :myscope } open_all_myscope_user_subscriptions POST /myscope/users/:user_id/subscriptions(.:format) { controller:"activity_notification/subscriptions", action:"create", target_type:"users", routing_scope: :myscope } myscope_user_subscription DELETE /myscope/users/:user_id/subscriptions/:id(.:format) { controller:"activity_notification/subscriptions", action:"destroy", target_type:"users", routing_scope: :myscope } subscribe_myscope_user_subscription POST /myscope/users/:user_id/subscriptions/:id/subscribe(.:format) { controller:"activity_notification/subscriptions", action:"subscribe", target_type:"users", routing_scope: :myscope } unsubscribe_myscope_user_subscription POST /myscope/users/:user_id/subscriptions/:id/unsubscribe(.:format) { controller:"activity_notification/subscriptions", action:"unsubscribe", target_type:"users", routing_scope: :myscope } subscribe_to_email_myscope_user_subscription POST /myscope/users/:user_id/subscriptions/:id/subscribe_to_email(.:format) { controller:"activity_notification/subscriptions", action:"subscribe_to_email", target_type:"users", routing_scope: :myscope } unsubscribe_to_email_myscope_user_subscription POST /myscope/users/:user_id/subscriptions/:id/unsubscribe_to_email(.:format) { controller:"activity_notification/subscriptions", action:"unsubscribe_to_email", target_type:"users", routing_scope: :myscope } subscribe_to_optional_target_myscope_user_subscription POST /myscope/users/:user_id/subscriptions/:id/subscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions", action:"subscribe_to_optional_target", target_type:"users", routing_scope: :myscope } unsubscribe_to_optional_target_myscope_user_subscription POST /myscope/users/:user_id/subscriptions/:id/unsubscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions", action:"unsubscribe_to_optional_target", target_type:"users", routing_scope: :myscope } When you use devise authentication and you want make subscription targets assciated with devise, you can create as follows in your routes: subscribed_by :users, with_devise: :users This with_devise option creates the needed routes assciated with devise authentication: # Subscription with devise routes user_subscriptions GET /users/:user_id/subscriptions(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"index", target_type:"users", devise_type:"users" } user_subscription GET /users/:user_id/subscriptions/:id(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"show", target_type:"users", devise_type:"users" } open_all_user_subscriptions POST /users/:user_id/subscriptions(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"create", target_type:"users", devise_type:"users" } user_subscription DELETE /users/:user_id/subscriptions/:id(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"destroy", target_type:"users", devise_type:"users" } subscribe_user_subscription POST /users/:user_id/subscriptions/:id/subscribe(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"subscribe", target_type:"users", devise_type:"users" } unsubscribe_user_subscription POST /users/:user_id/subscriptions/:id/unsubscribe(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"unsubscribe", target_type:"users", devise_type:"users" } subscribe_to_email_user_subscription POST /users/:user_id/subscriptions/:id/subscribe_to_email(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"subscribe_to_email", target_type:"users", devise_type:"users" } unsubscribe_to_email_user_subscription POST /users/:user_id/subscriptions/:id/unsubscribe_to_email(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"unsubscribe_to_email", target_type:"users", devise_type:"users" } subscribe_to_optional_target_user_subscription POST /users/:user_id/subscriptions/:id/subscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"subscribe_to_optional_target", target_type:"users", devise_type:"users" } unsubscribe_to_optional_target_user_subscription POST /users/:user_id/subscriptions/:id/unsubscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"unsubscribe_to_optional_target", target_type:"users", devise_type:"users" } When you use with_devise option and you want to make simple default routes as follows, you can use devise_default_routes option: subscribed_by :users, with_devise: :users, devise_default_routes: true These with_devise and devise_default_routes options create the needed routes assciated with authenticated devise resource as the default target # Subscription with devise routes user_subscriptions GET /subscriptions(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"index", target_type:"users", devise_type:"users" } user_subscription GET /subscriptions/:id(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"show", target_type:"users", devise_type:"users" } open_all_user_subscriptions POST /subscriptions(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"create", target_type:"users", devise_type:"users" } user_subscription DELETE /subscriptions/:id(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"destroy", target_type:"users", devise_type:"users" } subscribe_user_subscription POST /subscriptions/:id/subscribe(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"subscribe", target_type:"users", devise_type:"users" } unsubscribe_user_subscription POST /subscriptions/:id/unsubscribe(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"unsubscribe", target_type:"users", devise_type:"users" } subscribe_to_email_user_subscription POST /subscriptions/:id/subscribe_to_email(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"subscribe_to_email", target_type:"users", devise_type:"users" } unsubscribe_to_email_user_subscription POST /subscriptions/:id/unsubscribe_to_email(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"unsubscribe_to_email", target_type:"users", devise_type:"users" } subscribe_to_optional_target_user_subscription POST /subscriptions/:id/subscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"subscribe_to_optional_target", target_type:"users", devise_type:"users" } unsubscribe_to_optional_target_user_subscription POST /subscriptions/:id/unsubscribe_to_optional_target(.:format) { controller:"activity_notification/subscriptions_with_devise", action:"unsubscribe_to_optional_target", target_type:"users", devise_type:"users" } @example Define subscribed_by in config/routes.rb subscribed_by :users @example Define subscribed_by with options subscribed_by :users, except: [:index, :show] @example Integrated with Devise authentication subscribed_by :users, with_devise: :users @overload subscribed_by(*resources, *options) @param [Symbol] resources Resources to notify @option options [String] :routing_scope (nil) Routing scope for subscription routes @option options [Symbol] :with_devise (false) Devise resources name for devise integration. Devise integration will be enabled by this option. @option options [Boolean] :devise_default_routes (false) Whether you will create routes as device default routes assciated with authenticated devise resource as the default target @option options [String] :model (:subscriptions) Model name of subscriptions @option options [String] :controller ("activity_notification/subscriptions" | activity_notification/subscriptions_with_devise") :controller option as resources routing @option options [Symbol] :as (nil) :as option as resources routing @option options [Array] :only (nil) :only option as resources routing @option options [Array] :except (nil) :except option as resources routing @return [ActionDispatch::Routing::Mapper] Routing mapper instance
[ "Includes", "subscribed_by", "method", "for", "routes", "which", "is", "responsible", "to", "generate", "all", "necessary", "routes", "for", "subscriptions", "of", "activity_notification", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/rails/routes.rb#L264-L280
14,611
simukappu/activity_notification
lib/activity_notification/renderable.rb
ActivityNotification.Renderable.text
def text(params = {}) k = key.split('.') k.unshift('notification') if k.first != 'notification' if params.has_key?(:target) k.insert(1, params[:target]) else k.insert(1, target.to_resource_name) end k.push('text') k = k.join('.') attrs = (parameters.symbolize_keys.merge(params) || {}).merge( group_member_count: group_member_count, group_notification_count: group_notification_count, group_member_notifier_count: group_member_notifier_count, group_notifier_count: group_notifier_count ) # Generate the :default fallback key without using pluralization key :count default = I18n.t(k, attrs) I18n.t(k, attrs.merge(count: group_notification_count, default: default)) end
ruby
def text(params = {}) k = key.split('.') k.unshift('notification') if k.first != 'notification' if params.has_key?(:target) k.insert(1, params[:target]) else k.insert(1, target.to_resource_name) end k.push('text') k = k.join('.') attrs = (parameters.symbolize_keys.merge(params) || {}).merge( group_member_count: group_member_count, group_notification_count: group_notification_count, group_member_notifier_count: group_member_notifier_count, group_notifier_count: group_notifier_count ) # Generate the :default fallback key without using pluralization key :count default = I18n.t(k, attrs) I18n.t(k, attrs.merge(count: group_notification_count, default: default)) end
[ "def", "text", "(", "params", "=", "{", "}", ")", "k", "=", "key", ".", "split", "(", "'.'", ")", "k", ".", "unshift", "(", "'notification'", ")", "if", "k", ".", "first", "!=", "'notification'", "if", "params", ".", "has_key?", "(", ":target", ")", "k", ".", "insert", "(", "1", ",", "params", "[", ":target", "]", ")", "else", "k", ".", "insert", "(", "1", ",", "target", ".", "to_resource_name", ")", "end", "k", ".", "push", "(", "'text'", ")", "k", "=", "k", ".", "join", "(", "'.'", ")", "attrs", "=", "(", "parameters", ".", "symbolize_keys", ".", "merge", "(", "params", ")", "||", "{", "}", ")", ".", "merge", "(", "group_member_count", ":", "group_member_count", ",", "group_notification_count", ":", "group_notification_count", ",", "group_member_notifier_count", ":", "group_member_notifier_count", ",", "group_notifier_count", ":", "group_notifier_count", ")", "# Generate the :default fallback key without using pluralization key :count", "default", "=", "I18n", ".", "t", "(", "k", ",", "attrs", ")", "I18n", ".", "t", "(", "k", ",", "attrs", ".", "merge", "(", "count", ":", "group_notification_count", ",", "default", ":", "default", ")", ")", "end" ]
Virtual attribute returning text description of the notification using the notification's key to translate using i18n. @param [Hash] params Parameters for rendering notification text @option params [String] :target Target type name to use as i18n text key @option params [Hash] others Parameters to be referred in i18n text @return [String] Rendered text
[ "Virtual", "attribute", "returning", "text", "description", "of", "the", "notification", "using", "the", "notification", "s", "key", "to", "translate", "using", "i18n", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/renderable.rb#L13-L34
14,612
simukappu/activity_notification
lib/activity_notification/renderable.rb
ActivityNotification.Renderable.render
def render(context, params = {}) params[:i18n] and return context.render plain: self.text(params) partial = partial_path(*params.values_at(:partial, :partial_root, :target)) layout = layout_path(*params.values_at(:layout, :layout_root)) locals = prepare_locals(params) begin context.render params.merge(partial: partial, layout: layout, locals: locals) rescue ActionView::MissingTemplate => e if params[:fallback] == :text context.render plain: self.text(params) elsif params[:fallback].present? partial = partial_path(*params.values_at(:fallback, :partial_root, :target)) context.render params.merge(partial: partial, layout: layout, locals: locals) else raise e end end end
ruby
def render(context, params = {}) params[:i18n] and return context.render plain: self.text(params) partial = partial_path(*params.values_at(:partial, :partial_root, :target)) layout = layout_path(*params.values_at(:layout, :layout_root)) locals = prepare_locals(params) begin context.render params.merge(partial: partial, layout: layout, locals: locals) rescue ActionView::MissingTemplate => e if params[:fallback] == :text context.render plain: self.text(params) elsif params[:fallback].present? partial = partial_path(*params.values_at(:fallback, :partial_root, :target)) context.render params.merge(partial: partial, layout: layout, locals: locals) else raise e end end end
[ "def", "render", "(", "context", ",", "params", "=", "{", "}", ")", "params", "[", ":i18n", "]", "and", "return", "context", ".", "render", "plain", ":", "self", ".", "text", "(", "params", ")", "partial", "=", "partial_path", "(", "params", ".", "values_at", "(", ":partial", ",", ":partial_root", ",", ":target", ")", ")", "layout", "=", "layout_path", "(", "params", ".", "values_at", "(", ":layout", ",", ":layout_root", ")", ")", "locals", "=", "prepare_locals", "(", "params", ")", "begin", "context", ".", "render", "params", ".", "merge", "(", "partial", ":", "partial", ",", "layout", ":", "layout", ",", "locals", ":", "locals", ")", "rescue", "ActionView", "::", "MissingTemplate", "=>", "e", "if", "params", "[", ":fallback", "]", "==", ":text", "context", ".", "render", "plain", ":", "self", ".", "text", "(", "params", ")", "elsif", "params", "[", ":fallback", "]", ".", "present?", "partial", "=", "partial_path", "(", "params", ".", "values_at", "(", ":fallback", ",", ":partial_root", ",", ":target", ")", ")", "context", ".", "render", "params", ".", "merge", "(", "partial", ":", "partial", ",", "layout", ":", "layout", ",", "locals", ":", "locals", ")", "else", "raise", "e", "end", "end", "end" ]
Renders notification from views. The preferred way of rendering notifications is to provide a template specifying how the rendering should be happening. However, you can choose using _i18n_ based approach when developing an application that supports plenty of languages. If partial view exists that matches the "target" type and "key" attribute renders that partial with local variables set to contain both Notification and notification_parameters (hash with indifferent access). If the partial view does not exist and you wish to fallback to rendering through the i18n translation, you can do so by passing in a :fallback parameter whose value equals :text. If you do not want to define a partial view, and instead want to have all missing views fallback to a default, you can define the :fallback value equal to the partial you wish to use when the partial defined by the notification key does not exist. Render a list of all notifications of @target from a view (erb): <ul> <% @target.notifications.each do |notification| %> <li><%= render_notification notification %></li> <% end %> </ul> Fallback to the i18n text translation if the view is missing: <ul> <% @target.notifications.each do |notification| %> <li><%= render_notification notification, fallback: :text %></li> <% end %> </ul> Fallback to a default view if the view for the current notification key is missing: <ul> <% @target.notifications.each do |notification| %> <li><%= render_notification notification, fallback: 'default' %></li> <% end %> </ul> = Layouts You can supply a layout that will be used for notification partials with :layout param. Keep in mind that layouts for partials are also partials. Supply a layout: # in views: # All examples look for a layout in app/views/layouts/_notification.erb render_notification @notification, layout: "notification" render_notification @notification, layout: "layouts/notification" render_notification @notification, layout: :notification # app/views/layouts/_notification.erb <p><%= notification.created_at %></p> <%= yield %> == Custom Layout Location You can customize the layout directory by supplying :layout_root or by using an absolute path. Declare custom layout location: # Both examples look for a layout in "app/views/custom/_layout.erb" render_notification @notification, layout_root: "custom" render_notification @notification, layout: "/custom/layout" = Creating a template To use templates for formatting how the notification should render, create a template based on target type and notification key, for example: Given a target type users and key _notification.article.create_, create directory tree _app/views/activity_notification/notifications/users/article/_ and create the _create_ partial there Note that if a key consists of more than three parts splitted by commas, your directory structure will have to be deeper, for example: notification.article.comment.reply => app/views/activity_notification/notifications/users/article/comment/_reply.html.erb == Custom Directory You can override the default `activity_notification/notifications/#{target}` template root with the :partial_root parameter. Custom template root: # look for templates inside of /app/views/custom instead of /app/views/public_directory/activity_notification/notifications/#{target} render_notification @notification, partial_root: "custom" == Variables in templates From within a template there are three variables at your disposal: * notification * controller * parameters [converted into a HashWithIndifferentAccess] Template for key: _notification.article.create_ (erb): <p> Article <strong><%= parameters[:title] %></strong> was posted by <em><%= parameters["author"] %></em> <%= distance_of_time_in_words_to_now(notification.created_at) %> </p> @param [ActionView::Base] context @param [Hash] params Parameters for rendering notifications @option params [String, Symbol] :target (nil) Target type name to find template or i18n text @option params [String] :partial_root ("activity_notification/notifications/#{target}", controller.target_view_path, 'activity_notification/notifications/default') Partial template name @option params [String] :partial (self.key.tr('.', '/')) Root path of partial template @option params [String] :layout (nil) Layout template name @option params [String] :layout_root ('layouts') Root path of layout template @option params [String, Symbol] :fallback (nil) Fallback template to use when MissingTemplate is raised. Set :text to use i18n text as fallback. @option params [Hash] others Parameters to be set as locals @return [String] Rendered view or text as string
[ "Renders", "notification", "from", "views", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/renderable.rb#L148-L167
14,613
simukappu/activity_notification
lib/activity_notification/renderable.rb
ActivityNotification.Renderable.partial_path
def partial_path(path = nil, root = nil, target = nil) controller = ActivityNotification.get_controller if ActivityNotification.respond_to?(:get_controller) root ||= "activity_notification/notifications/#{target}" if target.present? root ||= controller.target_view_path if controller.present? && controller.respond_to?(:target_view_path) root ||= 'activity_notification/notifications/default' template_key = notifiable.respond_to?(:overriding_notification_template_key) && notifiable.overriding_notification_template_key(@target, key).present? ? notifiable.overriding_notification_template_key(@target, key) : key path ||= template_key.tr('.', '/') select_path(path, root) end
ruby
def partial_path(path = nil, root = nil, target = nil) controller = ActivityNotification.get_controller if ActivityNotification.respond_to?(:get_controller) root ||= "activity_notification/notifications/#{target}" if target.present? root ||= controller.target_view_path if controller.present? && controller.respond_to?(:target_view_path) root ||= 'activity_notification/notifications/default' template_key = notifiable.respond_to?(:overriding_notification_template_key) && notifiable.overriding_notification_template_key(@target, key).present? ? notifiable.overriding_notification_template_key(@target, key) : key path ||= template_key.tr('.', '/') select_path(path, root) end
[ "def", "partial_path", "(", "path", "=", "nil", ",", "root", "=", "nil", ",", "target", "=", "nil", ")", "controller", "=", "ActivityNotification", ".", "get_controller", "if", "ActivityNotification", ".", "respond_to?", "(", ":get_controller", ")", "root", "||=", "\"activity_notification/notifications/#{target}\"", "if", "target", ".", "present?", "root", "||=", "controller", ".", "target_view_path", "if", "controller", ".", "present?", "&&", "controller", ".", "respond_to?", "(", ":target_view_path", ")", "root", "||=", "'activity_notification/notifications/default'", "template_key", "=", "notifiable", ".", "respond_to?", "(", ":overriding_notification_template_key", ")", "&&", "notifiable", ".", "overriding_notification_template_key", "(", "@target", ",", "key", ")", ".", "present?", "?", "notifiable", ".", "overriding_notification_template_key", "(", "@target", ",", "key", ")", ":", "key", "path", "||=", "template_key", ".", "tr", "(", "'.'", ",", "'/'", ")", "select_path", "(", "path", ",", "root", ")", "end" ]
Returns partial path from options @param [String] path Partial template name @param [String] root Root path of partial template @param [String, Symbol] target Target type name to find template @return [String] Partial template path
[ "Returns", "partial", "path", "from", "options" ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/renderable.rb#L175-L186
14,614
simukappu/activity_notification
lib/activity_notification/common.rb
ActivityNotification.Common.resolve_value
def resolve_value(thing, *args) case thing when Symbol symbol_method = method(thing) if symbol_method.arity > 0 symbol_method.call(*args) else symbol_method.call end when Proc if thing.arity > 1 thing.call(self, *args) elsif thing.arity > 0 thing.call(self) else thing.call end when Hash thing.dup.tap do |hash| hash.each do |key, value| hash[key] = resolve_value(value, *args) end end else thing end end
ruby
def resolve_value(thing, *args) case thing when Symbol symbol_method = method(thing) if symbol_method.arity > 0 symbol_method.call(*args) else symbol_method.call end when Proc if thing.arity > 1 thing.call(self, *args) elsif thing.arity > 0 thing.call(self) else thing.call end when Hash thing.dup.tap do |hash| hash.each do |key, value| hash[key] = resolve_value(value, *args) end end else thing end end
[ "def", "resolve_value", "(", "thing", ",", "*", "args", ")", "case", "thing", "when", "Symbol", "symbol_method", "=", "method", "(", "thing", ")", "if", "symbol_method", ".", "arity", ">", "0", "symbol_method", ".", "call", "(", "args", ")", "else", "symbol_method", ".", "call", "end", "when", "Proc", "if", "thing", ".", "arity", ">", "1", "thing", ".", "call", "(", "self", ",", "args", ")", "elsif", "thing", ".", "arity", ">", "0", "thing", ".", "call", "(", "self", ")", "else", "thing", ".", "call", "end", "when", "Hash", "thing", ".", "dup", ".", "tap", "do", "|", "hash", "|", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "hash", "[", "key", "]", "=", "resolve_value", "(", "value", ",", "args", ")", "end", "end", "else", "thing", "end", "end" ]
Used to transform value from metadata to data which belongs model instance. Accepts Symbols, which it will send against this instance, Accepts Procs, which it will execute with this instance. Both Symbols and Procs will be passed arguments of this method. Also accepts Hash of these Symbols or Procs. If any other value will be passed, returns original value. @param [Symbol, Proc, Hash, Object] thing Symbol or Proc to resolve parameter @param [Array] args Arguments to pass to thing as method @return [Object] Resolved parameter value
[ "Used", "to", "transform", "value", "from", "metadata", "to", "data", "which", "belongs", "model", "instance", ".", "Accepts", "Symbols", "which", "it", "will", "send", "against", "this", "instance", "Accepts", "Procs", "which", "it", "will", "execute", "with", "this", "instance", ".", "Both", "Symbols", "and", "Procs", "will", "be", "passed", "arguments", "of", "this", "method", ".", "Also", "accepts", "Hash", "of", "these", "Symbols", "or", "Procs", ".", "If", "any", "other", "value", "will", "be", "passed", "returns", "original", "value", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/common.rb#L72-L98
14,615
simukappu/activity_notification
app/controllers/activity_notification/notifications_controller.rb
ActivityNotification.NotificationsController.index
def index set_index_options load_index if params[:reload].to_s.to_boolean(true) respond_to do |format| format.html # index.html.erb format.json { render json: @notifications.to_json(include: [:target, :notifiable, :group]) } end end
ruby
def index set_index_options load_index if params[:reload].to_s.to_boolean(true) respond_to do |format| format.html # index.html.erb format.json { render json: @notifications.to_json(include: [:target, :notifiable, :group]) } end end
[ "def", "index", "set_index_options", "load_index", "if", "params", "[", ":reload", "]", ".", "to_s", ".", "to_boolean", "(", "true", ")", "respond_to", "do", "|", "format", "|", "format", ".", "html", "# index.html.erb", "format", ".", "json", "{", "render", "json", ":", "@notifications", ".", "to_json", "(", "include", ":", "[", ":target", ",", ":notifiable", ",", ":group", "]", ")", "}", "end", "end" ]
Shows notification index of the target. GET /:target_type/:target_id/notifications @overload index(params) @param [Hash] params Request parameter options for notification index @option params [String] :filter (nil) Filter option to load notification index (Nothing as auto, 'opened' or 'unopened') @option params [String] :limit (nil) Limit to query for notifications @option params [String] :reverse ('false') If notification index will be ordered as earliest first @option params [String] :without_grouping ('false') If notification index will include group members @option params [String] :with_group_members ('false') If notification index will include group members @option params [String] :filtered_by_type (nil) Notifiable type for filter @option params [String] :filtered_by_group_type (nil) Group type for filter, valid with :filtered_by_group_id @option params [String] :filtered_by_group_id (nil) Group instance id for filter, valid with :filtered_by_group_type @option params [String] :filtered_by_key (nil) Key of the notification for filter @option params [String] :reload ('true') Whether notification index will be reloaded @return [Responce] HTML view as default or JSON of notification index with json format parameter
[ "Shows", "notification", "index", "of", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/notifications_controller.rb#L24-L31
14,616
simukappu/activity_notification
app/controllers/activity_notification/notifications_controller.rb
ActivityNotification.NotificationsController.open
def open with_members = !(params[:with_group_members].to_s.to_boolean(false) || params[:without_grouping].to_s.to_boolean(false)) @notification.open!(with_members: with_members) params[:move].to_s.to_boolean(false) ? move : return_back_or_ajax end
ruby
def open with_members = !(params[:with_group_members].to_s.to_boolean(false) || params[:without_grouping].to_s.to_boolean(false)) @notification.open!(with_members: with_members) params[:move].to_s.to_boolean(false) ? move : return_back_or_ajax end
[ "def", "open", "with_members", "=", "!", "(", "params", "[", ":with_group_members", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", "||", "params", "[", ":without_grouping", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", ")", "@notification", ".", "open!", "(", "with_members", ":", "with_members", ")", "params", "[", ":move", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", "?", "move", ":", "return_back_or_ajax", "end" ]
Opens a notification. POST /:target_type/:target_id/notifications/:id/open @overload open(params) @param [Hash] params Request parameters @option params [String] :move ('false') Whether redirects to notifiable_path after the notification is opened @option params [String] :filter (nil) Filter option to load notification index (Nothing as auto, 'opened' or 'unopened') @option params [String] :limit (nil) Limit to query for notifications @option params [String] :reload ('true') Whether notification index will be reloaded @option params [String] :without_grouping ('false') If notification index will include group members @option params [String] :with_group_members ('false') If notification index will include group members @return [Responce] JavaScript view for ajax request or redirects to back as default
[ "Opens", "a", "notification", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/notifications_controller.rb#L91-L97
14,617
simukappu/activity_notification
app/controllers/activity_notification/notifications_controller.rb
ActivityNotification.NotificationsController.set_index_options
def set_index_options limit = params[:limit].to_i > 0 ? params[:limit].to_i : nil reverse = params[:reverse].present? ? params[:reverse].to_s.to_boolean(false) : nil with_group_members = params[:with_group_members].present? || params[:without_grouping].present? ? params[:with_group_members].to_s.to_boolean(false) || params[:without_grouping].to_s.to_boolean(false) : nil @index_options = params.permit(:filter, :filtered_by_type, :filtered_by_group_type, :filtered_by_group_id, :filtered_by_key, :routing_scope, :devise_default_routes) .to_h.symbolize_keys .merge(limit: limit, reverse: reverse, with_group_members: with_group_members) end
ruby
def set_index_options limit = params[:limit].to_i > 0 ? params[:limit].to_i : nil reverse = params[:reverse].present? ? params[:reverse].to_s.to_boolean(false) : nil with_group_members = params[:with_group_members].present? || params[:without_grouping].present? ? params[:with_group_members].to_s.to_boolean(false) || params[:without_grouping].to_s.to_boolean(false) : nil @index_options = params.permit(:filter, :filtered_by_type, :filtered_by_group_type, :filtered_by_group_id, :filtered_by_key, :routing_scope, :devise_default_routes) .to_h.symbolize_keys .merge(limit: limit, reverse: reverse, with_group_members: with_group_members) end
[ "def", "set_index_options", "limit", "=", "params", "[", ":limit", "]", ".", "to_i", ">", "0", "?", "params", "[", ":limit", "]", ".", "to_i", ":", "nil", "reverse", "=", "params", "[", ":reverse", "]", ".", "present?", "?", "params", "[", ":reverse", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", ":", "nil", "with_group_members", "=", "params", "[", ":with_group_members", "]", ".", "present?", "||", "params", "[", ":without_grouping", "]", ".", "present?", "?", "params", "[", ":with_group_members", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", "||", "params", "[", ":without_grouping", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", ":", "nil", "@index_options", "=", "params", ".", "permit", "(", ":filter", ",", ":filtered_by_type", ",", ":filtered_by_group_type", ",", ":filtered_by_group_id", ",", ":filtered_by_key", ",", ":routing_scope", ",", ":devise_default_routes", ")", ".", "to_h", ".", "symbolize_keys", ".", "merge", "(", "limit", ":", "limit", ",", "reverse", ":", "reverse", ",", "with_group_members", ":", "with_group_members", ")", "end" ]
Sets options to load notification index from request parameters. @api protected @return [Hash] options to load notification index
[ "Sets", "options", "to", "load", "notification", "index", "from", "request", "parameters", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/notifications_controller.rb#L132-L141
14,618
simukappu/activity_notification
lib/activity_notification/models/concerns/target.rb
ActivityNotification.Target.authenticated_with_devise?
def authenticated_with_devise?(current_resource) devise_resource = resolve_value(_notification_devise_resource) unless current_resource.blank? or current_resource.is_a? devise_resource.class raise TypeError, "Different type of current resource #{current_resource.class} "\ "with devise resource #{devise_resource.class} has been passed to #{self.class}##{__method__}. "\ "You have to override #{self.class}##{__method__} method or set devise_resource in acts_as_target." end current_resource.present? && current_resource == devise_resource end
ruby
def authenticated_with_devise?(current_resource) devise_resource = resolve_value(_notification_devise_resource) unless current_resource.blank? or current_resource.is_a? devise_resource.class raise TypeError, "Different type of current resource #{current_resource.class} "\ "with devise resource #{devise_resource.class} has been passed to #{self.class}##{__method__}. "\ "You have to override #{self.class}##{__method__} method or set devise_resource in acts_as_target." end current_resource.present? && current_resource == devise_resource end
[ "def", "authenticated_with_devise?", "(", "current_resource", ")", "devise_resource", "=", "resolve_value", "(", "_notification_devise_resource", ")", "unless", "current_resource", ".", "blank?", "or", "current_resource", ".", "is_a?", "devise_resource", ".", "class", "raise", "TypeError", ",", "\"Different type of current resource #{current_resource.class} \"", "\"with devise resource #{devise_resource.class} has been passed to #{self.class}##{__method__}. \"", "\"You have to override #{self.class}##{__method__} method or set devise_resource in acts_as_target.\"", "end", "current_resource", ".", "present?", "&&", "current_resource", "==", "devise_resource", "end" ]
Returns if current resource signed in with Devise is authenticated for the notification. This method is able to be overriden. @param [Object] current_resource Current resource signed in with Devise @return [Boolean] If current resource signed in with Devise is authenticated for the notification
[ "Returns", "if", "current", "resource", "signed", "in", "with", "Devise", "is", "authenticated", "for", "the", "notification", ".", "This", "method", "is", "able", "to", "be", "overriden", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/target.rb#L194-L203
14,619
simukappu/activity_notification
lib/activity_notification/models/concerns/target.rb
ActivityNotification.Target.send_batch_notification_email
def send_batch_notification_email(notifications, options = {}) return if notifications.blank? if notifications.map{ |n| n.target }.uniq == [self] Notification.send_batch_notification_email(self, notifications, options) end end
ruby
def send_batch_notification_email(notifications, options = {}) return if notifications.blank? if notifications.map{ |n| n.target }.uniq == [self] Notification.send_batch_notification_email(self, notifications, options) end end
[ "def", "send_batch_notification_email", "(", "notifications", ",", "options", "=", "{", "}", ")", "return", "if", "notifications", ".", "blank?", "if", "notifications", ".", "map", "{", "|", "n", "|", "n", ".", "target", "}", ".", "uniq", "==", "[", "self", "]", "Notification", ".", "send_batch_notification_email", "(", "self", ",", "notifications", ",", "options", ")", "end", "end" ]
Sends batch notification email to the target. @param [Array<Notification>] notifications Target notifications to send batch notification email @param [Hash] options Options for notification email @option options [Boolean] :send_later (false) If it sends notification email asynchronously @option options [String, Symbol] :fallback (:batch_default) Fallback template to use when MissingTemplate is raised @option options [String] :batch_key (nil) Key of the batch notification email, a key of the first notification will be used if not specified @return [Mail::Message|ActionMailer::DeliveryJob|NilClass] Email message or its delivery job, return NilClass for wrong target
[ "Sends", "batch", "notification", "email", "to", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/target.rb#L462-L467
14,620
simukappu/activity_notification
lib/activity_notification/models/concerns/target.rb
ActivityNotification.Target.subscribes_to_notification?
def subscribes_to_notification?(key, subscribe_as_default = ActivityNotification.config.subscribe_as_default) !subscription_allowed?(key) || _subscribes_to_notification?(key, subscribe_as_default) end
ruby
def subscribes_to_notification?(key, subscribe_as_default = ActivityNotification.config.subscribe_as_default) !subscription_allowed?(key) || _subscribes_to_notification?(key, subscribe_as_default) end
[ "def", "subscribes_to_notification?", "(", "key", ",", "subscribe_as_default", "=", "ActivityNotification", ".", "config", ".", "subscribe_as_default", ")", "!", "subscription_allowed?", "(", "key", ")", "||", "_subscribes_to_notification?", "(", "key", ",", "subscribe_as_default", ")", "end" ]
Returns if the target subscribes to the notification. It also returns true when the subscription management is not allowed for the target. @param [String] key Key of the notification @param [Boolean] subscribe_as_default Default subscription value to use when the subscription record does not configured @return [Boolean] If the target subscribes the notification or the subscription management is not allowed for the target
[ "Returns", "if", "the", "target", "subscribes", "to", "the", "notification", ".", "It", "also", "returns", "true", "when", "the", "subscription", "management", "is", "not", "allowed", "for", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/target.rb#L475-L477
14,621
simukappu/activity_notification
lib/activity_notification/models/concerns/target.rb
ActivityNotification.Target.subscribes_to_notification_email?
def subscribes_to_notification_email?(key, subscribe_as_default = ActivityNotification.config.subscribe_as_default) !subscription_allowed?(key) || _subscribes_to_notification_email?(key, subscribe_as_default) end
ruby
def subscribes_to_notification_email?(key, subscribe_as_default = ActivityNotification.config.subscribe_as_default) !subscription_allowed?(key) || _subscribes_to_notification_email?(key, subscribe_as_default) end
[ "def", "subscribes_to_notification_email?", "(", "key", ",", "subscribe_as_default", "=", "ActivityNotification", ".", "config", ".", "subscribe_as_default", ")", "!", "subscription_allowed?", "(", "key", ")", "||", "_subscribes_to_notification_email?", "(", "key", ",", "subscribe_as_default", ")", "end" ]
Returns if the target subscribes to the notification email. It also returns true when the subscription management is not allowed for the target. @param [String] key Key of the notification @param [Boolean] subscribe_as_default Default subscription value to use when the subscription record does not configured @return [Boolean] If the target subscribes the notification email or the subscription management is not allowed for the target
[ "Returns", "if", "the", "target", "subscribes", "to", "the", "notification", "email", ".", "It", "also", "returns", "true", "when", "the", "subscription", "management", "is", "not", "allowed", "for", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/target.rb#L485-L487
14,622
simukappu/activity_notification
lib/activity_notification/models/concerns/target.rb
ActivityNotification.Target.subscribes_to_optional_target?
def subscribes_to_optional_target?(key, optional_target_name, subscribe_as_default = ActivityNotification.config.subscribe_as_default) !subscription_allowed?(key) || _subscribes_to_optional_target?(key, optional_target_name, subscribe_as_default) end
ruby
def subscribes_to_optional_target?(key, optional_target_name, subscribe_as_default = ActivityNotification.config.subscribe_as_default) !subscription_allowed?(key) || _subscribes_to_optional_target?(key, optional_target_name, subscribe_as_default) end
[ "def", "subscribes_to_optional_target?", "(", "key", ",", "optional_target_name", ",", "subscribe_as_default", "=", "ActivityNotification", ".", "config", ".", "subscribe_as_default", ")", "!", "subscription_allowed?", "(", "key", ")", "||", "_subscribes_to_optional_target?", "(", "key", ",", "optional_target_name", ",", "subscribe_as_default", ")", "end" ]
Returns if the target subscribes to the specified optional target. It also returns true when the subscription management is not allowed for the target. @param [String] key Key of the notification @param [String, Symbol] optional_target_name Class name of the optional target implementation (e.g. :amazon_sns, :slack) @param [Boolean] subscribe_as_default Default subscription value to use when the subscription record does not configured @return [Boolean] If the target subscribes the notification email or the subscription management is not allowed for the target
[ "Returns", "if", "the", "target", "subscribes", "to", "the", "specified", "optional", "target", ".", "It", "also", "returns", "true", "when", "the", "subscription", "management", "is", "not", "allowed", "for", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/target.rb#L497-L499
14,623
simukappu/activity_notification
lib/activity_notification/models/concerns/target.rb
ActivityNotification.Target._opened_notification_index
def _opened_notification_index(options = {}) limit = options[:limit] || ActivityNotification.config.opened_index_limit reverse = options[:reverse] || false with_group_members = options[:with_group_members] || false notifications.opened_index(limit, reverse, with_group_members).filtered_by_options(options) end
ruby
def _opened_notification_index(options = {}) limit = options[:limit] || ActivityNotification.config.opened_index_limit reverse = options[:reverse] || false with_group_members = options[:with_group_members] || false notifications.opened_index(limit, reverse, with_group_members).filtered_by_options(options) end
[ "def", "_opened_notification_index", "(", "options", "=", "{", "}", ")", "limit", "=", "options", "[", ":limit", "]", "||", "ActivityNotification", ".", "config", ".", "opened_index_limit", "reverse", "=", "options", "[", ":reverse", "]", "||", "false", "with_group_members", "=", "options", "[", ":with_group_members", "]", "||", "false", "notifications", ".", "opened_index", "(", "limit", ",", "reverse", ",", "with_group_members", ")", ".", "filtered_by_options", "(", "options", ")", "end" ]
Gets opened notification index of the target as ActiveRecord. @param [Hash] options Options for notification index @option options [Integer] :limit (nil) Limit to query for notifications @option options [Boolean] :reverse (false) If notification index will be ordered as earliest first @option options [Boolean] :with_group_members (false) If notification index will include group members @option options [String] :filtered_by_type (nil) Notifiable type for filter @option options [Object] :filtered_by_group (nil) Group instance for filter @option options [String] :filtered_by_group_type (nil) Group type for filter, valid with :filtered_by_group_id @option options [String] :filtered_by_group_id (nil) Group instance id for filter, valid with :filtered_by_group_type @option options [String] :filtered_by_key (nil) Key of the notification for filter @option options [Array|Hash] :custom_filter (nil) Custom notification filter (e.g. ["created_at >= ?", time.hour.ago]) @return [Array<Notificaion>] Opened notification index of the target
[ "Gets", "opened", "notification", "index", "of", "the", "target", "as", "ActiveRecord", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/target.rb#L537-L542
14,624
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.subscribe
def subscribe(options = {}) subscribed_at = options[:subscribed_at] || Time.current with_email_subscription = options.has_key?(:with_email_subscription) ? options[:with_email_subscription] : true with_optional_targets = options.has_key?(:with_optional_targets) ? options[:with_optional_targets] : true new_attributes = { subscribing: true, subscribed_at: subscribed_at, optional_targets: optional_targets } new_attributes = new_attributes.merge(subscribing_to_email: true, subscribed_to_email_at: subscribed_at) if with_email_subscription if with_optional_targets optional_target_names.each do |optional_target_name| new_attributes[:optional_targets] = new_attributes[:optional_targets].merge( Subscription.to_optional_target_key(optional_target_name) => true, Subscription.to_optional_target_subscribed_at_key(optional_target_name) => subscribed_at) end end update(new_attributes) end
ruby
def subscribe(options = {}) subscribed_at = options[:subscribed_at] || Time.current with_email_subscription = options.has_key?(:with_email_subscription) ? options[:with_email_subscription] : true with_optional_targets = options.has_key?(:with_optional_targets) ? options[:with_optional_targets] : true new_attributes = { subscribing: true, subscribed_at: subscribed_at, optional_targets: optional_targets } new_attributes = new_attributes.merge(subscribing_to_email: true, subscribed_to_email_at: subscribed_at) if with_email_subscription if with_optional_targets optional_target_names.each do |optional_target_name| new_attributes[:optional_targets] = new_attributes[:optional_targets].merge( Subscription.to_optional_target_key(optional_target_name) => true, Subscription.to_optional_target_subscribed_at_key(optional_target_name) => subscribed_at) end end update(new_attributes) end
[ "def", "subscribe", "(", "options", "=", "{", "}", ")", "subscribed_at", "=", "options", "[", ":subscribed_at", "]", "||", "Time", ".", "current", "with_email_subscription", "=", "options", ".", "has_key?", "(", ":with_email_subscription", ")", "?", "options", "[", ":with_email_subscription", "]", ":", "true", "with_optional_targets", "=", "options", ".", "has_key?", "(", ":with_optional_targets", ")", "?", "options", "[", ":with_optional_targets", "]", ":", "true", "new_attributes", "=", "{", "subscribing", ":", "true", ",", "subscribed_at", ":", "subscribed_at", ",", "optional_targets", ":", "optional_targets", "}", "new_attributes", "=", "new_attributes", ".", "merge", "(", "subscribing_to_email", ":", "true", ",", "subscribed_to_email_at", ":", "subscribed_at", ")", "if", "with_email_subscription", "if", "with_optional_targets", "optional_target_names", ".", "each", "do", "|", "optional_target_name", "|", "new_attributes", "[", ":optional_targets", "]", "=", "new_attributes", "[", ":optional_targets", "]", ".", "merge", "(", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "=>", "true", ",", "Subscription", ".", "to_optional_target_subscribed_at_key", "(", "optional_target_name", ")", "=>", "subscribed_at", ")", "end", "end", "update", "(", "new_attributes", ")", "end" ]
Subscribes to the notification and notification email. @param [Hash] options Options for subscribing to the notification @option options [DateTime] :subscribed_at (Time.current) Time to set to subscribed_at and subscribed_to_email_at of the subscription record @option options [Boolean] :with_email_subscription (true) If the subscriber also subscribes notification email @option options [Boolean] :with_optional_targets (true) If the subscriber also subscribes optional_targets @return [Boolean] If successfully updated subscription instance
[ "Subscribes", "to", "the", "notification", "and", "notification", "email", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L88-L102
14,625
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.unsubscribe
def unsubscribe(options = {}) unsubscribed_at = options[:unsubscribed_at] || Time.current new_attributes = { subscribing: false, unsubscribed_at: unsubscribed_at, subscribing_to_email: false, unsubscribed_to_email_at: unsubscribed_at, optional_targets: optional_targets } optional_target_names.each do |optional_target_name| new_attributes[:optional_targets] = new_attributes[:optional_targets].merge( Subscription.to_optional_target_key(optional_target_name) => false, Subscription.to_optional_target_unsubscribed_at_key(optional_target_name) => subscribed_at) end update(new_attributes) end
ruby
def unsubscribe(options = {}) unsubscribed_at = options[:unsubscribed_at] || Time.current new_attributes = { subscribing: false, unsubscribed_at: unsubscribed_at, subscribing_to_email: false, unsubscribed_to_email_at: unsubscribed_at, optional_targets: optional_targets } optional_target_names.each do |optional_target_name| new_attributes[:optional_targets] = new_attributes[:optional_targets].merge( Subscription.to_optional_target_key(optional_target_name) => false, Subscription.to_optional_target_unsubscribed_at_key(optional_target_name) => subscribed_at) end update(new_attributes) end
[ "def", "unsubscribe", "(", "options", "=", "{", "}", ")", "unsubscribed_at", "=", "options", "[", ":unsubscribed_at", "]", "||", "Time", ".", "current", "new_attributes", "=", "{", "subscribing", ":", "false", ",", "unsubscribed_at", ":", "unsubscribed_at", ",", "subscribing_to_email", ":", "false", ",", "unsubscribed_to_email_at", ":", "unsubscribed_at", ",", "optional_targets", ":", "optional_targets", "}", "optional_target_names", ".", "each", "do", "|", "optional_target_name", "|", "new_attributes", "[", ":optional_targets", "]", "=", "new_attributes", "[", ":optional_targets", "]", ".", "merge", "(", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "=>", "false", ",", "Subscription", ".", "to_optional_target_unsubscribed_at_key", "(", "optional_target_name", ")", "=>", "subscribed_at", ")", "end", "update", "(", "new_attributes", ")", "end" ]
Unsubscribes to the notification and notification email. @param [Hash] options Options for unsubscribing to the notification @option options [DateTime] :unsubscribed_at (Time.current) Time to set to unsubscribed_at and unsubscribed_to_email_at of the subscription record @return [Boolean] If successfully updated subscription instance
[ "Unsubscribes", "to", "the", "notification", "and", "notification", "email", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L109-L120
14,626
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.subscribe_to_email
def subscribe_to_email(options = {}) subscribed_to_email_at = options[:subscribed_to_email_at] || Time.current update(subscribing_to_email: true, subscribed_to_email_at: subscribed_to_email_at) end
ruby
def subscribe_to_email(options = {}) subscribed_to_email_at = options[:subscribed_to_email_at] || Time.current update(subscribing_to_email: true, subscribed_to_email_at: subscribed_to_email_at) end
[ "def", "subscribe_to_email", "(", "options", "=", "{", "}", ")", "subscribed_to_email_at", "=", "options", "[", ":subscribed_to_email_at", "]", "||", "Time", ".", "current", "update", "(", "subscribing_to_email", ":", "true", ",", "subscribed_to_email_at", ":", "subscribed_to_email_at", ")", "end" ]
Subscribes to the notification email. @param [Hash] options Options for subscribing to the notification email @option options [DateTime] :subscribed_to_email_at (Time.current) Time to set to subscribed_to_email_at of the subscription record @return [Boolean] If successfully updated subscription instance
[ "Subscribes", "to", "the", "notification", "email", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L127-L130
14,627
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.unsubscribe_to_email
def unsubscribe_to_email(options = {}) unsubscribed_to_email_at = options[:unsubscribed_to_email_at] || Time.current update(subscribing_to_email: false, unsubscribed_to_email_at: unsubscribed_to_email_at) end
ruby
def unsubscribe_to_email(options = {}) unsubscribed_to_email_at = options[:unsubscribed_to_email_at] || Time.current update(subscribing_to_email: false, unsubscribed_to_email_at: unsubscribed_to_email_at) end
[ "def", "unsubscribe_to_email", "(", "options", "=", "{", "}", ")", "unsubscribed_to_email_at", "=", "options", "[", ":unsubscribed_to_email_at", "]", "||", "Time", ".", "current", "update", "(", "subscribing_to_email", ":", "false", ",", "unsubscribed_to_email_at", ":", "unsubscribed_to_email_at", ")", "end" ]
Unsubscribes to the notification email. @param [Hash] options Options for unsubscribing the notification email @option options [DateTime] :subscribed_to_email_at (Time.current) Time to set to subscribed_to_email_at of the subscription record @return [Boolean] If successfully updated subscription instance
[ "Unsubscribes", "to", "the", "notification", "email", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L137-L140
14,628
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.subscribing_to_optional_target?
def subscribing_to_optional_target?(optional_target_name, subscribe_as_default = ActivityNotification.config.subscribe_as_default) optional_target_key = Subscription.to_optional_target_key(optional_target_name) subscribe_as_default ? !optional_targets.has_key?(optional_target_key) || optional_targets[optional_target_key] : optional_targets.has_key?(optional_target_key) && optional_targets[optional_target_key] end
ruby
def subscribing_to_optional_target?(optional_target_name, subscribe_as_default = ActivityNotification.config.subscribe_as_default) optional_target_key = Subscription.to_optional_target_key(optional_target_name) subscribe_as_default ? !optional_targets.has_key?(optional_target_key) || optional_targets[optional_target_key] : optional_targets.has_key?(optional_target_key) && optional_targets[optional_target_key] end
[ "def", "subscribing_to_optional_target?", "(", "optional_target_name", ",", "subscribe_as_default", "=", "ActivityNotification", ".", "config", ".", "subscribe_as_default", ")", "optional_target_key", "=", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "subscribe_as_default", "?", "!", "optional_targets", ".", "has_key?", "(", "optional_target_key", ")", "||", "optional_targets", "[", "optional_target_key", "]", ":", "optional_targets", ".", "has_key?", "(", "optional_target_key", ")", "&&", "optional_targets", "[", "optional_target_key", "]", "end" ]
Returns if the target subscribes to the specified optional target. @param [Symbol] optional_target_name Symbol class name of the optional target implementation (e.g. :amazon_sns, :slack) @param [Boolean] subscribe_as_default Default subscription value to use when the subscription record does not configured @return [Boolean] If the target subscribes to the specified optional target
[ "Returns", "if", "the", "target", "subscribes", "to", "the", "specified", "optional", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L147-L152
14,629
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.subscribe_to_optional_target
def subscribe_to_optional_target(optional_target_name, options = {}) subscribed_at = options[:subscribed_at] || Time.current update(optional_targets: optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => true, Subscription.to_optional_target_subscribed_at_key(optional_target_name) => subscribed_at) ) end
ruby
def subscribe_to_optional_target(optional_target_name, options = {}) subscribed_at = options[:subscribed_at] || Time.current update(optional_targets: optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => true, Subscription.to_optional_target_subscribed_at_key(optional_target_name) => subscribed_at) ) end
[ "def", "subscribe_to_optional_target", "(", "optional_target_name", ",", "options", "=", "{", "}", ")", "subscribed_at", "=", "options", "[", ":subscribed_at", "]", "||", "Time", ".", "current", "update", "(", "optional_targets", ":", "optional_targets", ".", "merge", "(", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "=>", "true", ",", "Subscription", ".", "to_optional_target_subscribed_at_key", "(", "optional_target_name", ")", "=>", "subscribed_at", ")", ")", "end" ]
Subscribes to the specified optional target. @param [String, Symbol] optional_target_name Symbol class name of the optional target implementation (e.g. :amazon_sns, :slack) @param [Hash] options Options for unsubscribing to the specified optional target @option options [DateTime] :subscribed_at (Time.current) Time to set to subscribed_[optional_target_name]_at in optional_targets hash of the subscription record @return [Boolean] If successfully updated subscription instance
[ "Subscribes", "to", "the", "specified", "optional", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L160-L166
14,630
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.unsubscribe_to_optional_target
def unsubscribe_to_optional_target(optional_target_name, options = {}) unsubscribed_at = options[:unsubscribed_at] || Time.current update(optional_targets: optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => false, Subscription.to_optional_target_unsubscribed_at_key(optional_target_name) => unsubscribed_at) ) end
ruby
def unsubscribe_to_optional_target(optional_target_name, options = {}) unsubscribed_at = options[:unsubscribed_at] || Time.current update(optional_targets: optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => false, Subscription.to_optional_target_unsubscribed_at_key(optional_target_name) => unsubscribed_at) ) end
[ "def", "unsubscribe_to_optional_target", "(", "optional_target_name", ",", "options", "=", "{", "}", ")", "unsubscribed_at", "=", "options", "[", ":unsubscribed_at", "]", "||", "Time", ".", "current", "update", "(", "optional_targets", ":", "optional_targets", ".", "merge", "(", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "=>", "false", ",", "Subscription", ".", "to_optional_target_unsubscribed_at_key", "(", "optional_target_name", ")", "=>", "unsubscribed_at", ")", ")", "end" ]
Unsubscribes to the specified optional target. @param [String, Symbol] optional_target_name Class name of the optional target implementation (e.g. :amazon_sns, :slack) @param [Hash] options Options for unsubscribing to the specified optional target @option options [DateTime] :unsubscribed_at (Time.current) Time to set to unsubscribed_[optional_target_name]_at in optional_targets hash of the subscription record @return [Boolean] If successfully updated subscription instance
[ "Unsubscribes", "to", "the", "specified", "optional", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L174-L180
14,631
simukappu/activity_notification
lib/activity_notification/apis/subscription_api.rb
ActivityNotification.SubscriptionApi.optional_target_names
def optional_target_names optional_targets.keys.select { |key| key.to_s.start_with?("subscribing_to_") }.map { |key| key.slice(15..-1) } end
ruby
def optional_target_names optional_targets.keys.select { |key| key.to_s.start_with?("subscribing_to_") }.map { |key| key.slice(15..-1) } end
[ "def", "optional_target_names", "optional_targets", ".", "keys", ".", "select", "{", "|", "key", "|", "key", ".", "to_s", ".", "start_with?", "(", "\"subscribing_to_\"", ")", "}", ".", "map", "{", "|", "key", "|", "key", ".", "slice", "(", "15", "..", "-", "1", ")", "}", "end" ]
Returns optional_target names of the subscription from optional_targets field. @return [Array<Symbol>] Array of optional target names
[ "Returns", "optional_target", "names", "of", "the", "subscription", "from", "optional_targets", "field", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/apis/subscription_api.rb#L184-L186
14,632
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.notification_targets
def notification_targets(target_type, options = {}) target_typed_method_name = "notification_#{cast_to_resources_name(target_type)}" resolved_parameter = resolve_parameter( target_typed_method_name, _notification_targets[cast_to_resources_sym(target_type)], nil, options) unless resolved_parameter raise NotImplementedError, "You have to implement #{self.class}##{target_typed_method_name} "\ "or set :targets in acts_as_notifiable" end resolved_parameter end
ruby
def notification_targets(target_type, options = {}) target_typed_method_name = "notification_#{cast_to_resources_name(target_type)}" resolved_parameter = resolve_parameter( target_typed_method_name, _notification_targets[cast_to_resources_sym(target_type)], nil, options) unless resolved_parameter raise NotImplementedError, "You have to implement #{self.class}##{target_typed_method_name} "\ "or set :targets in acts_as_notifiable" end resolved_parameter end
[ "def", "notification_targets", "(", "target_type", ",", "options", "=", "{", "}", ")", "target_typed_method_name", "=", "\"notification_#{cast_to_resources_name(target_type)}\"", "resolved_parameter", "=", "resolve_parameter", "(", "target_typed_method_name", ",", "_notification_targets", "[", "cast_to_resources_sym", "(", "target_type", ")", "]", ",", "nil", ",", "options", ")", "unless", "resolved_parameter", "raise", "NotImplementedError", ",", "\"You have to implement #{self.class}##{target_typed_method_name} \"", "\"or set :targets in acts_as_notifiable\"", "end", "resolved_parameter", "end" ]
Returns notification targets from configured field or overriden method. This method is able to be overriden. @param [String] target_type Target type to notify @param [Hash] options Options for notifications @option options [String] :key (notifiable.default_notification_key) Key of the notification @option options [Hash] :parameters ({}) Additional parameters of the notifications @return [Array<Notificaion> | ActiveRecord_AssociationRelation<Notificaion>] Array or database query of the notification targets
[ "Returns", "notification", "targets", "from", "configured", "field", "or", "overriden", "method", ".", "This", "method", "is", "able", "to", "be", "overriden", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L71-L83
14,633
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.notification_email_allowed?
def notification_email_allowed?(target, key = nil) resolve_parameter( "notification_email_allowed_for_#{cast_to_resources_name(target.class)}?", _notification_email_allowed[cast_to_resources_sym(target.class)], ActivityNotification.config.email_enabled, target, key) end
ruby
def notification_email_allowed?(target, key = nil) resolve_parameter( "notification_email_allowed_for_#{cast_to_resources_name(target.class)}?", _notification_email_allowed[cast_to_resources_sym(target.class)], ActivityNotification.config.email_enabled, target, key) end
[ "def", "notification_email_allowed?", "(", "target", ",", "key", "=", "nil", ")", "resolve_parameter", "(", "\"notification_email_allowed_for_#{cast_to_resources_name(target.class)}?\"", ",", "_notification_email_allowed", "[", "cast_to_resources_sym", "(", "target", ".", "class", ")", "]", ",", "ActivityNotification", ".", "config", ".", "email_enabled", ",", "target", ",", "key", ")", "end" ]
Returns if sending notification email is allowed for the notifiable from configured field or overriden method. This method is able to be overriden. @param [Object] target Target instance to notify @param [String] key Key of the notification @return [Boolean] If sending notification email is allowed for the notifiable
[ "Returns", "if", "sending", "notification", "email", "is", "allowed", "for", "the", "notifiable", "from", "configured", "field", "or", "overriden", "method", ".", "This", "method", "is", "able", "to", "be", "overriden", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L147-L153
14,634
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.notifiable_path
def notifiable_path(target_type, key = nil) resolved_parameter = resolve_parameter( "notifiable_path_for_#{cast_to_resources_name(target_type)}", _notifiable_path[cast_to_resources_sym(target_type)], nil, key) unless resolved_parameter begin resolved_parameter = defined?(super) ? super : polymorphic_path(self) rescue NoMethodError, ActionController::UrlGenerationError raise NotImplementedError, "You have to implement #{self.class}##{__method__}, "\ "set :notifiable_path in acts_as_notifiable or "\ "set polymorphic_path routing for #{self.class}" end end resolved_parameter end
ruby
def notifiable_path(target_type, key = nil) resolved_parameter = resolve_parameter( "notifiable_path_for_#{cast_to_resources_name(target_type)}", _notifiable_path[cast_to_resources_sym(target_type)], nil, key) unless resolved_parameter begin resolved_parameter = defined?(super) ? super : polymorphic_path(self) rescue NoMethodError, ActionController::UrlGenerationError raise NotImplementedError, "You have to implement #{self.class}##{__method__}, "\ "set :notifiable_path in acts_as_notifiable or "\ "set polymorphic_path routing for #{self.class}" end end resolved_parameter end
[ "def", "notifiable_path", "(", "target_type", ",", "key", "=", "nil", ")", "resolved_parameter", "=", "resolve_parameter", "(", "\"notifiable_path_for_#{cast_to_resources_name(target_type)}\"", ",", "_notifiable_path", "[", "cast_to_resources_sym", "(", "target_type", ")", "]", ",", "nil", ",", "key", ")", "unless", "resolved_parameter", "begin", "resolved_parameter", "=", "defined?", "(", "super", ")", "?", "super", ":", "polymorphic_path", "(", "self", ")", "rescue", "NoMethodError", ",", "ActionController", "::", "UrlGenerationError", "raise", "NotImplementedError", ",", "\"You have to implement #{self.class}##{__method__}, \"", "\"set :notifiable_path in acts_as_notifiable or \"", "\"set polymorphic_path routing for #{self.class}\"", "end", "end", "resolved_parameter", "end" ]
Returns notifiable_path to move after opening notification from configured field or overriden method. This method is able to be overriden. @param [String] target_type Target type to notify @param [String] key Key of the notification @return [String] Notifiable path URL to move after opening notification
[ "Returns", "notifiable_path", "to", "move", "after", "opening", "notification", "from", "configured", "field", "or", "overriden", "method", ".", "This", "method", "is", "able", "to", "be", "overriden", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L161-L177
14,635
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.printable_notifiable_name
def printable_notifiable_name(target, key = nil) resolve_parameter( "printable_notifiable_name_for_#{cast_to_resources_name(target.class)}?", _printable_notifiable_name[cast_to_resources_sym(target.class)], printable_name, target, key) end
ruby
def printable_notifiable_name(target, key = nil) resolve_parameter( "printable_notifiable_name_for_#{cast_to_resources_name(target.class)}?", _printable_notifiable_name[cast_to_resources_sym(target.class)], printable_name, target, key) end
[ "def", "printable_notifiable_name", "(", "target", ",", "key", "=", "nil", ")", "resolve_parameter", "(", "\"printable_notifiable_name_for_#{cast_to_resources_name(target.class)}?\"", ",", "_printable_notifiable_name", "[", "cast_to_resources_sym", "(", "target", ".", "class", ")", "]", ",", "printable_name", ",", "target", ",", "key", ")", "end" ]
Returns printable notifiable model name to show in view or email. @return [String] Printable notifiable model name
[ "Returns", "printable", "notifiable", "model", "name", "to", "show", "in", "view", "or", "email", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L181-L187
14,636
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.optional_target_names
def optional_target_names(target_type, key = nil) optional_targets(target_type, key).map { |optional_target| optional_target.to_optional_target_name } end
ruby
def optional_target_names(target_type, key = nil) optional_targets(target_type, key).map { |optional_target| optional_target.to_optional_target_name } end
[ "def", "optional_target_names", "(", "target_type", ",", "key", "=", "nil", ")", "optional_targets", "(", "target_type", ",", "key", ")", ".", "map", "{", "|", "optional_target", "|", "optional_target", ".", "to_optional_target_name", "}", "end" ]
Returns optional_target names of the notification from configured field or overriden method. This method is able to be overriden. @param [String] target_type Target type to notify @param [String] key Key of the notification @return [Array<Symbol>] Array of optional target names
[ "Returns", "optional_target", "names", "of", "the", "notification", "from", "configured", "field", "or", "overriden", "method", ".", "This", "method", "is", "able", "to", "be", "overriden", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L209-L211
14,637
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.generated_notifications_as_notifiable_for
def generated_notifications_as_notifiable_for(target_type = nil) target_type.nil? ? generated_notifications_as_notifiable.all : generated_notifications_as_notifiable.filtered_by_target_type(target_type.to_s.to_model_name) end
ruby
def generated_notifications_as_notifiable_for(target_type = nil) target_type.nil? ? generated_notifications_as_notifiable.all : generated_notifications_as_notifiable.filtered_by_target_type(target_type.to_s.to_model_name) end
[ "def", "generated_notifications_as_notifiable_for", "(", "target_type", "=", "nil", ")", "target_type", ".", "nil?", "?", "generated_notifications_as_notifiable", ".", "all", ":", "generated_notifications_as_notifiable", ".", "filtered_by_target_type", "(", "target_type", ".", "to_s", ".", "to_model_name", ")", "end" ]
Gets generated notifications for specified target type. @api private @param [String] target_type Target type of generated notifications
[ "Gets", "generated", "notifications", "for", "specified", "target", "type", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L405-L409
14,638
simukappu/activity_notification
lib/activity_notification/models/concerns/notifiable.rb
ActivityNotification.Notifiable.destroy_generated_notifications_with_dependency
def destroy_generated_notifications_with_dependency(dependent = :delete_all, target_type = nil, remove_from_group = false) remove_generated_notifications_from_group(target_type) if remove_from_group generated_notifications = generated_notifications_as_notifiable_for(target_type) case dependent when :restrict_with_exception ActivityNotification::Notification.raise_delete_restriction_error("generated_notifications_as_notifiable_for_#{target_type.to_s.pluralize.underscore}") unless generated_notifications.empty? when :restrict_with_error unless generated_notifications.empty? record = self.class.human_attribute_name("generated_notifications_as_notifiable_for_#{target_type.to_s.pluralize.underscore}").downcase self.errors.add(:base, :'restrict_dependent_destroy.has_many', record: record) # :only-rails5+: if Rails::VERSION::MAJOR >= 5 throw(:abort) # :only-rails5+: # :except-rails5+: else false end # :except-rails5+: end when :destroy generated_notifications.each { |n| n.destroy } when :delete_all generated_notifications.delete_all end end
ruby
def destroy_generated_notifications_with_dependency(dependent = :delete_all, target_type = nil, remove_from_group = false) remove_generated_notifications_from_group(target_type) if remove_from_group generated_notifications = generated_notifications_as_notifiable_for(target_type) case dependent when :restrict_with_exception ActivityNotification::Notification.raise_delete_restriction_error("generated_notifications_as_notifiable_for_#{target_type.to_s.pluralize.underscore}") unless generated_notifications.empty? when :restrict_with_error unless generated_notifications.empty? record = self.class.human_attribute_name("generated_notifications_as_notifiable_for_#{target_type.to_s.pluralize.underscore}").downcase self.errors.add(:base, :'restrict_dependent_destroy.has_many', record: record) # :only-rails5+: if Rails::VERSION::MAJOR >= 5 throw(:abort) # :only-rails5+: # :except-rails5+: else false end # :except-rails5+: end when :destroy generated_notifications.each { |n| n.destroy } when :delete_all generated_notifications.delete_all end end
[ "def", "destroy_generated_notifications_with_dependency", "(", "dependent", "=", ":delete_all", ",", "target_type", "=", "nil", ",", "remove_from_group", "=", "false", ")", "remove_generated_notifications_from_group", "(", "target_type", ")", "if", "remove_from_group", "generated_notifications", "=", "generated_notifications_as_notifiable_for", "(", "target_type", ")", "case", "dependent", "when", ":restrict_with_exception", "ActivityNotification", "::", "Notification", ".", "raise_delete_restriction_error", "(", "\"generated_notifications_as_notifiable_for_#{target_type.to_s.pluralize.underscore}\"", ")", "unless", "generated_notifications", ".", "empty?", "when", ":restrict_with_error", "unless", "generated_notifications", ".", "empty?", "record", "=", "self", ".", "class", ".", "human_attribute_name", "(", "\"generated_notifications_as_notifiable_for_#{target_type.to_s.pluralize.underscore}\"", ")", ".", "downcase", "self", ".", "errors", ".", "add", "(", ":base", ",", ":'", "'", ",", "record", ":", "record", ")", "# :only-rails5+:", "if", "Rails", "::", "VERSION", "::", "MAJOR", ">=", "5", "throw", "(", ":abort", ")", "# :only-rails5+:", "# :except-rails5+:", "else", "false", "end", "# :except-rails5+:", "end", "when", ":destroy", "generated_notifications", ".", "each", "{", "|", "n", "|", "n", ".", "destroy", "}", "when", ":delete_all", "generated_notifications", ".", "delete_all", "end", "end" ]
Destroies generated notifications for specified target type with dependency. This method is intended to be called before destroy this notifiable as dependent configuration. @api private @param [Symbol] dependent Has_many dependency, [:delete_all, :destroy, :restrict_with_error, :restrict_with_exception] are available @param [String] target_type Target type of generated notifications @param [Boolean] remove_from_group Whether it removes generated notifications from notification group before destroy
[ "Destroies", "generated", "notifications", "for", "specified", "target", "type", "with", "dependency", ".", "This", "method", "is", "intended", "to", "be", "called", "before", "destroy", "this", "notifiable", "as", "dependent", "configuration", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/notifiable.rb#L417-L442
14,639
simukappu/activity_notification
app/controllers/activity_notification/subscriptions_controller.rb
ActivityNotification.SubscriptionsController.index
def index set_index_options load_index if params[:reload].to_s.to_boolean(true) respond_to do |format| format.html # index.html.erb format.json { render json: { subscriptions: @subscriptions, unconfigured_notification_keys: @notification_keys } } end end
ruby
def index set_index_options load_index if params[:reload].to_s.to_boolean(true) respond_to do |format| format.html # index.html.erb format.json { render json: { subscriptions: @subscriptions, unconfigured_notification_keys: @notification_keys } } end end
[ "def", "index", "set_index_options", "load_index", "if", "params", "[", ":reload", "]", ".", "to_s", ".", "to_boolean", "(", "true", ")", "respond_to", "do", "|", "format", "|", "format", ".", "html", "# index.html.erb", "format", ".", "json", "{", "render", "json", ":", "{", "subscriptions", ":", "@subscriptions", ",", "unconfigured_notification_keys", ":", "@notification_keys", "}", "}", "end", "end" ]
Shows subscription index of the target. GET /:target_type/:target_id/subscriptions @overload index(params) @param [Hash] params Request parameter options for subscription index @option params [String] :filter (nil) Filter option to load subscription index (Nothing as all, 'configured' or 'unconfigured') @option params [String] :limit (nil) Limit to query for subscriptions @option params [String] :reverse ('false') If subscription index and unconfigured notification keys will be ordered as earliest first @option params [String] :filtered_by_key (nil) Key of the subscription for filter @return [Responce] HTML view as default or JSON of subscription index with json format parameter
[ "Shows", "subscription", "index", "of", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/subscriptions_controller.rb#L19-L26
14,640
simukappu/activity_notification
app/controllers/activity_notification/subscriptions_controller.rb
ActivityNotification.SubscriptionsController.subscribe
def subscribe @subscription.subscribe(with_email_subscription: params[:with_email_subscription].to_s.to_boolean(true), with_optional_targets: params[:with_optional_targets].to_s.to_boolean(true)) return_back_or_ajax end
ruby
def subscribe @subscription.subscribe(with_email_subscription: params[:with_email_subscription].to_s.to_boolean(true), with_optional_targets: params[:with_optional_targets].to_s.to_boolean(true)) return_back_or_ajax end
[ "def", "subscribe", "@subscription", ".", "subscribe", "(", "with_email_subscription", ":", "params", "[", ":with_email_subscription", "]", ".", "to_s", ".", "to_boolean", "(", "true", ")", ",", "with_optional_targets", ":", "params", "[", ":with_optional_targets", "]", ".", "to_s", ".", "to_boolean", "(", "true", ")", ")", "return_back_or_ajax", "end" ]
Subscribes to the notification. POST /:target_type/:target_id/subscriptions/:id/subscribe @overload open(params) @param [Hash] params Request parameters @option params [String] :with_email_subscription ('true') If the subscriber also subscribes notification email @option params [String] :with_optional_targets ('true') If the subscriber also subscribes optional targets @option params [String] :filter (nil) Filter option to load subscription index (Nothing as all, 'configured' or 'unconfigured') @option params [String] :limit (nil) Limit to query for subscriptions @option params [String] :reverse ('false') If subscription index and unconfigured notification keys will be ordered as earliest first @option params [String] :filtered_by_key (nil) Key of the subscription for filter @return [Responce] JavaScript view for ajax request or redirects to back as default
[ "Subscribes", "to", "the", "notification", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/subscriptions_controller.rb#L86-L90
14,641
simukappu/activity_notification
app/controllers/activity_notification/subscriptions_controller.rb
ActivityNotification.SubscriptionsController.set_index_options
def set_index_options limit = params[:limit].to_i > 0 ? params[:limit].to_i : nil reverse = params[:reverse].present? ? params[:reverse].to_s.to_boolean(false) : nil @index_options = params.permit(:filter, :filtered_by_key, :routing_scope, :devise_default_routes) .to_h.symbolize_keys.merge(limit: limit, reverse: reverse) end
ruby
def set_index_options limit = params[:limit].to_i > 0 ? params[:limit].to_i : nil reverse = params[:reverse].present? ? params[:reverse].to_s.to_boolean(false) : nil @index_options = params.permit(:filter, :filtered_by_key, :routing_scope, :devise_default_routes) .to_h.symbolize_keys.merge(limit: limit, reverse: reverse) end
[ "def", "set_index_options", "limit", "=", "params", "[", ":limit", "]", ".", "to_i", ">", "0", "?", "params", "[", ":limit", "]", ".", "to_i", ":", "nil", "reverse", "=", "params", "[", ":reverse", "]", ".", "present?", "?", "params", "[", ":reverse", "]", ".", "to_s", ".", "to_boolean", "(", "false", ")", ":", "nil", "@index_options", "=", "params", ".", "permit", "(", ":filter", ",", ":filtered_by_key", ",", ":routing_scope", ",", ":devise_default_routes", ")", ".", "to_h", ".", "symbolize_keys", ".", "merge", "(", "limit", ":", "limit", ",", "reverse", ":", "reverse", ")", "end" ]
Sets options to load subscription index from request parameters. @api protected @return [Hash] options to load subscription index
[ "Sets", "options", "to", "load", "subscription", "index", "from", "request", "parameters", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/subscriptions_controller.rb#L190-L196
14,642
simukappu/activity_notification
app/controllers/activity_notification/subscriptions_controller.rb
ActivityNotification.SubscriptionsController.load_index
def load_index case @index_options[:filter] when :configured, 'configured' @subscriptions = @target.subscription_index(@index_options.merge(with_target: true)) @notification_keys = nil when :unconfigured, 'unconfigured' @subscriptions = nil @notification_keys = @target.notification_keys(@index_options.merge(filter: :unconfigured)) else @subscriptions = @target.subscription_index(@index_options.merge(with_target: true)) @notification_keys = @target.notification_keys(@index_options.merge(filter: :unconfigured)) end end
ruby
def load_index case @index_options[:filter] when :configured, 'configured' @subscriptions = @target.subscription_index(@index_options.merge(with_target: true)) @notification_keys = nil when :unconfigured, 'unconfigured' @subscriptions = nil @notification_keys = @target.notification_keys(@index_options.merge(filter: :unconfigured)) else @subscriptions = @target.subscription_index(@index_options.merge(with_target: true)) @notification_keys = @target.notification_keys(@index_options.merge(filter: :unconfigured)) end end
[ "def", "load_index", "case", "@index_options", "[", ":filter", "]", "when", ":configured", ",", "'configured'", "@subscriptions", "=", "@target", ".", "subscription_index", "(", "@index_options", ".", "merge", "(", "with_target", ":", "true", ")", ")", "@notification_keys", "=", "nil", "when", ":unconfigured", ",", "'unconfigured'", "@subscriptions", "=", "nil", "@notification_keys", "=", "@target", ".", "notification_keys", "(", "@index_options", ".", "merge", "(", "filter", ":", ":unconfigured", ")", ")", "else", "@subscriptions", "=", "@target", ".", "subscription_index", "(", "@index_options", ".", "merge", "(", "with_target", ":", "true", ")", ")", "@notification_keys", "=", "@target", ".", "notification_keys", "(", "@index_options", ".", "merge", "(", "filter", ":", ":unconfigured", ")", ")", "end", "end" ]
Loads subscription index with request parameters. @api protected @return [Array] Array of subscription index
[ "Loads", "subscription", "index", "with", "request", "parameters", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/app/controllers/activity_notification/subscriptions_controller.rb#L201-L213
14,643
simukappu/activity_notification
lib/activity_notification/models/concerns/subscriber.rb
ActivityNotification.Subscriber.find_or_create_subscription
def find_or_create_subscription(key, subscription_params = {}) subscription = find_subscription(key) subscription || create_subscription(subscription_params.merge(key: key)) end
ruby
def find_or_create_subscription(key, subscription_params = {}) subscription = find_subscription(key) subscription || create_subscription(subscription_params.merge(key: key)) end
[ "def", "find_or_create_subscription", "(", "key", ",", "subscription_params", "=", "{", "}", ")", "subscription", "=", "find_subscription", "(", "key", ")", "subscription", "||", "create_subscription", "(", "subscription_params", ".", "merge", "(", "key", ":", "key", ")", ")", "end" ]
Gets subscription of the target and notification key. @param [Hash] key Key of the notification for subscription @param [Hash] subscription_params Parameters to create subscription record @return [Subscription] Found or created subscription instance
[ "Gets", "subscription", "of", "the", "target", "and", "notification", "key", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/subscriber.rb#L41-L44
14,644
simukappu/activity_notification
lib/activity_notification/models/concerns/subscriber.rb
ActivityNotification.Subscriber.create_subscription
def create_subscription(subscription_params = {}) created_at = Time.current if subscription_params[:subscribing] == false && subscription_params[:subscribing_to_email].nil? subscription_params[:subscribing_to_email] = subscription_params[:subscribing] end subscription = subscriptions.new(subscription_params) subscription.subscribing? ? subscription.assign_attributes(subscribing: true, subscribed_at: created_at) : subscription.assign_attributes(subscribing: false, unsubscribed_at: created_at) subscription.subscribing_to_email? ? subscription.assign_attributes(subscribing_to_email: true, subscribed_to_email_at: created_at) : subscription.assign_attributes(subscribing_to_email: false, unsubscribed_to_email_at: created_at) subscription.optional_targets = (subscription.optional_targets || {}).with_indifferent_access optional_targets = {}.with_indifferent_access subscription.optional_target_names.each do |optional_target_name| optional_targets = subscription.subscribing_to_optional_target?(optional_target_name) ? optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => true, Subscription.to_optional_target_subscribed_at_key(optional_target_name) => created_at ) : optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => false, Subscription.to_optional_target_unsubscribed_at_key(optional_target_name) => created_at ) end subscription.assign_attributes(optional_targets: optional_targets) subscription.save ? subscription : nil end
ruby
def create_subscription(subscription_params = {}) created_at = Time.current if subscription_params[:subscribing] == false && subscription_params[:subscribing_to_email].nil? subscription_params[:subscribing_to_email] = subscription_params[:subscribing] end subscription = subscriptions.new(subscription_params) subscription.subscribing? ? subscription.assign_attributes(subscribing: true, subscribed_at: created_at) : subscription.assign_attributes(subscribing: false, unsubscribed_at: created_at) subscription.subscribing_to_email? ? subscription.assign_attributes(subscribing_to_email: true, subscribed_to_email_at: created_at) : subscription.assign_attributes(subscribing_to_email: false, unsubscribed_to_email_at: created_at) subscription.optional_targets = (subscription.optional_targets || {}).with_indifferent_access optional_targets = {}.with_indifferent_access subscription.optional_target_names.each do |optional_target_name| optional_targets = subscription.subscribing_to_optional_target?(optional_target_name) ? optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => true, Subscription.to_optional_target_subscribed_at_key(optional_target_name) => created_at ) : optional_targets.merge( Subscription.to_optional_target_key(optional_target_name) => false, Subscription.to_optional_target_unsubscribed_at_key(optional_target_name) => created_at ) end subscription.assign_attributes(optional_targets: optional_targets) subscription.save ? subscription : nil end
[ "def", "create_subscription", "(", "subscription_params", "=", "{", "}", ")", "created_at", "=", "Time", ".", "current", "if", "subscription_params", "[", ":subscribing", "]", "==", "false", "&&", "subscription_params", "[", ":subscribing_to_email", "]", ".", "nil?", "subscription_params", "[", ":subscribing_to_email", "]", "=", "subscription_params", "[", ":subscribing", "]", "end", "subscription", "=", "subscriptions", ".", "new", "(", "subscription_params", ")", "subscription", ".", "subscribing?", "?", "subscription", ".", "assign_attributes", "(", "subscribing", ":", "true", ",", "subscribed_at", ":", "created_at", ")", ":", "subscription", ".", "assign_attributes", "(", "subscribing", ":", "false", ",", "unsubscribed_at", ":", "created_at", ")", "subscription", ".", "subscribing_to_email?", "?", "subscription", ".", "assign_attributes", "(", "subscribing_to_email", ":", "true", ",", "subscribed_to_email_at", ":", "created_at", ")", ":", "subscription", ".", "assign_attributes", "(", "subscribing_to_email", ":", "false", ",", "unsubscribed_to_email_at", ":", "created_at", ")", "subscription", ".", "optional_targets", "=", "(", "subscription", ".", "optional_targets", "||", "{", "}", ")", ".", "with_indifferent_access", "optional_targets", "=", "{", "}", ".", "with_indifferent_access", "subscription", ".", "optional_target_names", ".", "each", "do", "|", "optional_target_name", "|", "optional_targets", "=", "subscription", ".", "subscribing_to_optional_target?", "(", "optional_target_name", ")", "?", "optional_targets", ".", "merge", "(", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "=>", "true", ",", "Subscription", ".", "to_optional_target_subscribed_at_key", "(", "optional_target_name", ")", "=>", "created_at", ")", ":", "optional_targets", ".", "merge", "(", "Subscription", ".", "to_optional_target_key", "(", "optional_target_name", ")", "=>", "false", ",", "Subscription", ".", "to_optional_target_unsubscribed_at_key", "(", "optional_target_name", ")", "=>", "created_at", ")", "end", "subscription", ".", "assign_attributes", "(", "optional_targets", ":", "optional_targets", ")", "subscription", ".", "save", "?", "subscription", ":", "nil", "end" ]
Creates new subscription of the target. @param [Hash] subscription_params Parameters to create subscription record @return [Subscription] Created subscription instance
[ "Creates", "new", "subscription", "of", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/subscriber.rb#L50-L77
14,645
simukappu/activity_notification
lib/activity_notification/models/concerns/subscriber.rb
ActivityNotification.Subscriber.subscription_index
def subscription_index(options = {}) target_index = subscriptions.filtered_by_options(options) target_index = options[:reverse] ? target_index.earliest_order : target_index.latest_order target_index = target_index.with_target if options[:with_target] options[:limit].present? ? target_index.limit(options[:limit]).to_a : target_index.to_a end
ruby
def subscription_index(options = {}) target_index = subscriptions.filtered_by_options(options) target_index = options[:reverse] ? target_index.earliest_order : target_index.latest_order target_index = target_index.with_target if options[:with_target] options[:limit].present? ? target_index.limit(options[:limit]).to_a : target_index.to_a end
[ "def", "subscription_index", "(", "options", "=", "{", "}", ")", "target_index", "=", "subscriptions", ".", "filtered_by_options", "(", "options", ")", "target_index", "=", "options", "[", ":reverse", "]", "?", "target_index", ".", "earliest_order", ":", "target_index", ".", "latest_order", "target_index", "=", "target_index", ".", "with_target", "if", "options", "[", ":with_target", "]", "options", "[", ":limit", "]", ".", "present?", "?", "target_index", ".", "limit", "(", "options", "[", ":limit", "]", ")", ".", "to_a", ":", "target_index", ".", "to_a", "end" ]
Gets configured subscription index of the target. @example Get configured subscription index of the @user @subscriptions = @user.subscription_index @param [Hash] options Options for subscription index @option options [Integer] :limit (nil) Limit to query for subscriptions @option options [Boolean] :reverse (false) If subscription index will be ordered as earliest first @option options [String] :filtered_by_key (nil) Key of the notification for filter @option options [Array|Hash] :custom_filter (nil) Custom subscription filter (e.g. ["created_at >= ?", time.hour.ago]) @option options [Boolean] :with_target (false) If it includes target with subscriptions @return [Array<Notificaion>] Configured subscription index of the target
[ "Gets", "configured", "subscription", "index", "of", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/subscriber.rb#L91-L96
14,646
simukappu/activity_notification
lib/activity_notification/models/concerns/subscriber.rb
ActivityNotification.Subscriber.notification_keys
def notification_keys(options = {}) subscription_keys = subscriptions.uniq_keys target_notifications = notifications.filtered_by_options(options.select { |k, _| [:filtered_by_key, :custom_filter].include?(k) }) target_notifications = options[:reverse] ? target_notifications.earliest_order : target_notifications.latest_order target_notifications = options[:limit].present? ? target_notifications.limit(options[:limit] + subscription_keys.size) : target_notifications notification_keys = target_notifications.uniq_keys notification_keys = case options[:filter] when :configured, 'configured' notification_keys & subscription_keys when :unconfigured, 'unconfigured' notification_keys - subscription_keys else notification_keys end options[:limit].present? ? notification_keys.take(options[:limit]) : notification_keys end
ruby
def notification_keys(options = {}) subscription_keys = subscriptions.uniq_keys target_notifications = notifications.filtered_by_options(options.select { |k, _| [:filtered_by_key, :custom_filter].include?(k) }) target_notifications = options[:reverse] ? target_notifications.earliest_order : target_notifications.latest_order target_notifications = options[:limit].present? ? target_notifications.limit(options[:limit] + subscription_keys.size) : target_notifications notification_keys = target_notifications.uniq_keys notification_keys = case options[:filter] when :configured, 'configured' notification_keys & subscription_keys when :unconfigured, 'unconfigured' notification_keys - subscription_keys else notification_keys end options[:limit].present? ? notification_keys.take(options[:limit]) : notification_keys end
[ "def", "notification_keys", "(", "options", "=", "{", "}", ")", "subscription_keys", "=", "subscriptions", ".", "uniq_keys", "target_notifications", "=", "notifications", ".", "filtered_by_options", "(", "options", ".", "select", "{", "|", "k", ",", "_", "|", "[", ":filtered_by_key", ",", ":custom_filter", "]", ".", "include?", "(", "k", ")", "}", ")", "target_notifications", "=", "options", "[", ":reverse", "]", "?", "target_notifications", ".", "earliest_order", ":", "target_notifications", ".", "latest_order", "target_notifications", "=", "options", "[", ":limit", "]", ".", "present?", "?", "target_notifications", ".", "limit", "(", "options", "[", ":limit", "]", "+", "subscription_keys", ".", "size", ")", ":", "target_notifications", "notification_keys", "=", "target_notifications", ".", "uniq_keys", "notification_keys", "=", "case", "options", "[", ":filter", "]", "when", ":configured", ",", "'configured'", "notification_keys", "&", "subscription_keys", "when", ":unconfigured", ",", "'unconfigured'", "notification_keys", "-", "subscription_keys", "else", "notification_keys", "end", "options", "[", ":limit", "]", ".", "present?", "?", "notification_keys", ".", "take", "(", "options", "[", ":limit", "]", ")", ":", "notification_keys", "end" ]
Gets received notification keys of the target. @example Get unconfigured notification keys of the @user @notification_keys = @user.notification_keys(filter: :unconfigured) @param [Hash] options Options for unconfigured notification keys @option options [Integer] :limit (nil) Limit to query for subscriptions @option options [Boolean] :reverse (false) If notification keys will be ordered as earliest first @option options [Symbol|String] :filter (nil) Filter option to load notification keys (Nothing as all, 'configured' with configured subscriptions or 'unconfigured' without subscriptions) @option options [String] :filtered_by_key (nil) Key of the notification for filter @option options [Array|Hash] :custom_filter (nil) Custom subscription filter (e.g. ["created_at >= ?", time.hour.ago]) @return [Array<Notificaion>] Unconfigured notification keys of the target
[ "Gets", "received", "notification", "keys", "of", "the", "target", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/subscriber.rb#L110-L126
14,647
simukappu/activity_notification
lib/activity_notification/models/concerns/subscriber.rb
ActivityNotification.Subscriber.evaluate_subscription
def evaluate_subscription(record, field, default, *args) default ? record.blank? || record.send(field, *args) : record.present? && record.send(field, *args) end
ruby
def evaluate_subscription(record, field, default, *args) default ? record.blank? || record.send(field, *args) : record.present? && record.send(field, *args) end
[ "def", "evaluate_subscription", "(", "record", ",", "field", ",", "default", ",", "*", "args", ")", "default", "?", "record", ".", "blank?", "||", "record", ".", "send", "(", "field", ",", "args", ")", ":", "record", ".", "present?", "&&", "record", ".", "send", "(", "field", ",", "args", ")", "end" ]
Returns if the target subscribes. @api private @param [Boolean] record Subscription record @param [Symbol] field Evaluating subscription field or method of the record @param [Boolean] default Default subscription value to use when the subscription record does not configured @param [Array] args Arguments of evaluating subscription method @return [Boolean] If the target subscribes
[ "Returns", "if", "the", "target", "subscribes", "." ]
7f0f0ea8db1e69d7806f5b0685e226452714847a
https://github.com/simukappu/activity_notification/blob/7f0f0ea8db1e69d7806f5b0685e226452714847a/lib/activity_notification/models/concerns/subscriber.rb#L175-L177
14,648
puppetlabs/puppet-resource_api
lib/puppet/resource_api/glue.rb
Puppet::ResourceApi.ResourceShim.to_hierayaml
def to_hierayaml attributes = Hash[filtered_keys.map { |k| [k.to_s, values[k]] }] YAML.dump('type' => { title => attributes }).split("\n").drop(2).join("\n") + "\n" end
ruby
def to_hierayaml attributes = Hash[filtered_keys.map { |k| [k.to_s, values[k]] }] YAML.dump('type' => { title => attributes }).split("\n").drop(2).join("\n") + "\n" end
[ "def", "to_hierayaml", "attributes", "=", "Hash", "[", "filtered_keys", ".", "map", "{", "|", "k", "|", "[", "k", ".", "to_s", ",", "values", "[", "k", "]", "]", "}", "]", "YAML", ".", "dump", "(", "'type'", "=>", "{", "title", "=>", "attributes", "}", ")", ".", "split", "(", "\"\\n\"", ")", ".", "drop", "(", "2", ")", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "end" ]
Convert our resource to yaml for Hiera purposes.
[ "Convert", "our", "resource", "to", "yaml", "for", "Hiera", "purposes", "." ]
7180586da22baa4a78b73d30e7432724593a1754
https://github.com/puppetlabs/puppet-resource_api/blob/7180586da22baa4a78b73d30e7432724593a1754/lib/puppet/resource_api/glue.rb#L39-L42
14,649
puppetlabs/puppet-resource_api
lib/puppet/resource_api/glue.rb
Puppet::ResourceApi.ResourceShim.filtered_keys
def filtered_keys values.keys.reject { |k| k == :title || !attr_def[k] || (attr_def[k][:behaviour] == :namevar && @namevars.size == 1) } end
ruby
def filtered_keys values.keys.reject { |k| k == :title || !attr_def[k] || (attr_def[k][:behaviour] == :namevar && @namevars.size == 1) } end
[ "def", "filtered_keys", "values", ".", "keys", ".", "reject", "{", "|", "k", "|", "k", "==", ":title", "||", "!", "attr_def", "[", "k", "]", "||", "(", "attr_def", "[", "k", "]", "[", ":behaviour", "]", "==", ":namevar", "&&", "@namevars", ".", "size", "==", "1", ")", "}", "end" ]
attribute names that are not title or namevars
[ "attribute", "names", "that", "are", "not", "title", "or", "namevars" ]
7180586da22baa4a78b73d30e7432724593a1754
https://github.com/puppetlabs/puppet-resource_api/blob/7180586da22baa4a78b73d30e7432724593a1754/lib/puppet/resource_api/glue.rb#L52-L54
14,650
puppetlabs/puppet-resource_api
lib/puppet/resource_api/type_definition.rb
Puppet::ResourceApi.TypeDefinition.feature?
def feature?(feature) supported = (definition[:features] && definition[:features].include?(feature)) if supported Puppet.debug("#{definition[:name]} supports `#{feature}`") else Puppet.debug("#{definition[:name]} does not support `#{feature}`") end supported end
ruby
def feature?(feature) supported = (definition[:features] && definition[:features].include?(feature)) if supported Puppet.debug("#{definition[:name]} supports `#{feature}`") else Puppet.debug("#{definition[:name]} does not support `#{feature}`") end supported end
[ "def", "feature?", "(", "feature", ")", "supported", "=", "(", "definition", "[", ":features", "]", "&&", "definition", "[", ":features", "]", ".", "include?", "(", "feature", ")", ")", "if", "supported", "Puppet", ".", "debug", "(", "\"#{definition[:name]} supports `#{feature}`\"", ")", "else", "Puppet", ".", "debug", "(", "\"#{definition[:name]} does not support `#{feature}`\"", ")", "end", "supported", "end" ]
rubocop complains when this is named has_feature?
[ "rubocop", "complains", "when", "this", "is", "named", "has_feature?" ]
7180586da22baa4a78b73d30e7432724593a1754
https://github.com/puppetlabs/puppet-resource_api/blob/7180586da22baa4a78b73d30e7432724593a1754/lib/puppet/resource_api/type_definition.rb#L17-L25
14,651
puppetlabs/puppet-resource_api
lib/puppet/resource_api/type_definition.rb
Puppet::ResourceApi.BaseTypeDefinition.check_schema
def check_schema(resource, message_prefix = nil) namevars.each do |namevar| if resource[namevar].nil? raise Puppet::ResourceError, "`#{name}.get` did not return a value for the `#{namevar}` namevar attribute" end end message_prefix = 'Provider returned data that does not match the Type Schema' if message_prefix.nil? message = "#{message_prefix} for `#{name}[#{resource[namevars.first]}]`" rejected_keys = check_schema_keys(resource) bad_values = check_schema_values(resource) unless rejected_keys.empty? message += "\n Unknown attribute:\n" rejected_keys.each { |key, _value| message += " * #{key}\n" } end unless bad_values.empty? message += "\n Value type mismatch:\n" bad_values.each { |key, value| message += " * #{key}: #{value}\n" } end return if rejected_keys.empty? && bad_values.empty? notify_schema_errors(message) end
ruby
def check_schema(resource, message_prefix = nil) namevars.each do |namevar| if resource[namevar].nil? raise Puppet::ResourceError, "`#{name}.get` did not return a value for the `#{namevar}` namevar attribute" end end message_prefix = 'Provider returned data that does not match the Type Schema' if message_prefix.nil? message = "#{message_prefix} for `#{name}[#{resource[namevars.first]}]`" rejected_keys = check_schema_keys(resource) bad_values = check_schema_values(resource) unless rejected_keys.empty? message += "\n Unknown attribute:\n" rejected_keys.each { |key, _value| message += " * #{key}\n" } end unless bad_values.empty? message += "\n Value type mismatch:\n" bad_values.each { |key, value| message += " * #{key}: #{value}\n" } end return if rejected_keys.empty? && bad_values.empty? notify_schema_errors(message) end
[ "def", "check_schema", "(", "resource", ",", "message_prefix", "=", "nil", ")", "namevars", ".", "each", "do", "|", "namevar", "|", "if", "resource", "[", "namevar", "]", ".", "nil?", "raise", "Puppet", "::", "ResourceError", ",", "\"`#{name}.get` did not return a value for the `#{namevar}` namevar attribute\"", "end", "end", "message_prefix", "=", "'Provider returned data that does not match the Type Schema'", "if", "message_prefix", ".", "nil?", "message", "=", "\"#{message_prefix} for `#{name}[#{resource[namevars.first]}]`\"", "rejected_keys", "=", "check_schema_keys", "(", "resource", ")", "bad_values", "=", "check_schema_values", "(", "resource", ")", "unless", "rejected_keys", ".", "empty?", "message", "+=", "\"\\n Unknown attribute:\\n\"", "rejected_keys", ".", "each", "{", "|", "key", ",", "_value", "|", "message", "+=", "\" * #{key}\\n\"", "}", "end", "unless", "bad_values", ".", "empty?", "message", "+=", "\"\\n Value type mismatch:\\n\"", "bad_values", ".", "each", "{", "|", "key", ",", "value", "|", "message", "+=", "\" * #{key}: #{value}\\n\"", "}", "end", "return", "if", "rejected_keys", ".", "empty?", "&&", "bad_values", ".", "empty?", "notify_schema_errors", "(", "message", ")", "end" ]
validates a resource hash against its type schema
[ "validates", "a", "resource", "hash", "against", "its", "type", "schema" ]
7180586da22baa4a78b73d30e7432724593a1754
https://github.com/puppetlabs/puppet-resource_api/blob/7180586da22baa4a78b73d30e7432724593a1754/lib/puppet/resource_api/type_definition.rb#L127-L152
14,652
puppetlabs/puppet-resource_api
lib/puppet/resource_api/type_definition.rb
Puppet::ResourceApi.BaseTypeDefinition.check_schema_keys
def check_schema_keys(resource) rejected = [] resource.reject { |key| rejected << key if key != :title && attributes.key?(key) == false } rejected end
ruby
def check_schema_keys(resource) rejected = [] resource.reject { |key| rejected << key if key != :title && attributes.key?(key) == false } rejected end
[ "def", "check_schema_keys", "(", "resource", ")", "rejected", "=", "[", "]", "resource", ".", "reject", "{", "|", "key", "|", "rejected", "<<", "key", "if", "key", "!=", ":title", "&&", "attributes", ".", "key?", "(", "key", ")", "==", "false", "}", "rejected", "end" ]
Returns an array of keys that where not found in the type schema No longer modifies the resource passed in
[ "Returns", "an", "array", "of", "keys", "that", "where", "not", "found", "in", "the", "type", "schema", "No", "longer", "modifies", "the", "resource", "passed", "in" ]
7180586da22baa4a78b73d30e7432724593a1754
https://github.com/puppetlabs/puppet-resource_api/blob/7180586da22baa4a78b73d30e7432724593a1754/lib/puppet/resource_api/type_definition.rb#L167-L171
14,653
puppetlabs/puppet-resource_api
lib/puppet/resource_api/type_definition.rb
Puppet::ResourceApi.BaseTypeDefinition.check_schema_values
def check_schema_values(resource) bad_vals = {} resource.each do |key, value| next unless attributes[key] type = @data_type_cache[attributes[key][:type]] is_sensitive = (attributes[key].key?(:sensitive) && (attributes[key][:sensitive] == true)) error_message = Puppet::ResourceApi::DataTypeHandling.try_validate( type, value, '', ) if is_sensitive bad_vals[key] = '<< redacted value >> ' + error_message unless error_message.nil? else bad_vals[key] = value unless error_message.nil? end end bad_vals end
ruby
def check_schema_values(resource) bad_vals = {} resource.each do |key, value| next unless attributes[key] type = @data_type_cache[attributes[key][:type]] is_sensitive = (attributes[key].key?(:sensitive) && (attributes[key][:sensitive] == true)) error_message = Puppet::ResourceApi::DataTypeHandling.try_validate( type, value, '', ) if is_sensitive bad_vals[key] = '<< redacted value >> ' + error_message unless error_message.nil? else bad_vals[key] = value unless error_message.nil? end end bad_vals end
[ "def", "check_schema_values", "(", "resource", ")", "bad_vals", "=", "{", "}", "resource", ".", "each", "do", "|", "key", ",", "value", "|", "next", "unless", "attributes", "[", "key", "]", "type", "=", "@data_type_cache", "[", "attributes", "[", "key", "]", "[", ":type", "]", "]", "is_sensitive", "=", "(", "attributes", "[", "key", "]", ".", "key?", "(", ":sensitive", ")", "&&", "(", "attributes", "[", "key", "]", "[", ":sensitive", "]", "==", "true", ")", ")", "error_message", "=", "Puppet", "::", "ResourceApi", "::", "DataTypeHandling", ".", "try_validate", "(", "type", ",", "value", ",", "''", ",", ")", "if", "is_sensitive", "bad_vals", "[", "key", "]", "=", "'<< redacted value >> '", "+", "error_message", "unless", "error_message", ".", "nil?", "else", "bad_vals", "[", "key", "]", "=", "value", "unless", "error_message", ".", "nil?", "end", "end", "bad_vals", "end" ]
Returns a hash of keys and values that are not valid does not modify the resource passed in
[ "Returns", "a", "hash", "of", "keys", "and", "values", "that", "are", "not", "valid", "does", "not", "modify", "the", "resource", "passed", "in" ]
7180586da22baa4a78b73d30e7432724593a1754
https://github.com/puppetlabs/puppet-resource_api/blob/7180586da22baa4a78b73d30e7432724593a1754/lib/puppet/resource_api/type_definition.rb#L175-L193
14,654
lostisland/faraday_middleware
lib/faraday_middleware/response_middleware.rb
FaradayMiddleware.ResponseMiddleware.parse
def parse(body) if self.class.parser begin self.class.parser.call(body, @parser_options) rescue StandardError, SyntaxError => err raise err if err.is_a? SyntaxError and err.class.name != 'Psych::SyntaxError' raise Faraday::Error::ParsingError, err end else body end end
ruby
def parse(body) if self.class.parser begin self.class.parser.call(body, @parser_options) rescue StandardError, SyntaxError => err raise err if err.is_a? SyntaxError and err.class.name != 'Psych::SyntaxError' raise Faraday::Error::ParsingError, err end else body end end
[ "def", "parse", "(", "body", ")", "if", "self", ".", "class", ".", "parser", "begin", "self", ".", "class", ".", "parser", ".", "call", "(", "body", ",", "@parser_options", ")", "rescue", "StandardError", ",", "SyntaxError", "=>", "err", "raise", "err", "if", "err", ".", "is_a?", "SyntaxError", "and", "err", ".", "class", ".", "name", "!=", "'Psych::SyntaxError'", "raise", "Faraday", "::", "Error", "::", "ParsingError", ",", "err", "end", "else", "body", "end", "end" ]
Parse the response body. Instead of overriding this method, consider using `define_parser`.
[ "Parse", "the", "response", "body", "." ]
09b04ab68288205cc5579aaaf4138012f95268dd
https://github.com/lostisland/faraday_middleware/blob/09b04ab68288205cc5579aaaf4138012f95268dd/lib/faraday_middleware/response_middleware.rb#L48-L59
14,655
lostisland/faraday_middleware
lib/faraday_middleware/rack_compatible.rb
FaradayMiddleware.RackCompatible.prepare_env
def prepare_env(faraday_env) env = headers_to_rack(faraday_env) url = faraday_env[:url] env['rack.url_scheme'] = url.scheme env['PATH_INFO'] = url.path env['SERVER_PORT'] = url.respond_to?(:inferred_port) ? url.inferred_port : url.port env['QUERY_STRING'] = url.query env['REQUEST_METHOD'] = faraday_env[:method].to_s.upcase env['rack.errors'] ||= StringIO.new env['faraday'] = faraday_env env end
ruby
def prepare_env(faraday_env) env = headers_to_rack(faraday_env) url = faraday_env[:url] env['rack.url_scheme'] = url.scheme env['PATH_INFO'] = url.path env['SERVER_PORT'] = url.respond_to?(:inferred_port) ? url.inferred_port : url.port env['QUERY_STRING'] = url.query env['REQUEST_METHOD'] = faraday_env[:method].to_s.upcase env['rack.errors'] ||= StringIO.new env['faraday'] = faraday_env env end
[ "def", "prepare_env", "(", "faraday_env", ")", "env", "=", "headers_to_rack", "(", "faraday_env", ")", "url", "=", "faraday_env", "[", ":url", "]", "env", "[", "'rack.url_scheme'", "]", "=", "url", ".", "scheme", "env", "[", "'PATH_INFO'", "]", "=", "url", ".", "path", "env", "[", "'SERVER_PORT'", "]", "=", "url", ".", "respond_to?", "(", ":inferred_port", ")", "?", "url", ".", "inferred_port", ":", "url", ".", "port", "env", "[", "'QUERY_STRING'", "]", "=", "url", ".", "query", "env", "[", "'REQUEST_METHOD'", "]", "=", "faraday_env", "[", ":method", "]", ".", "to_s", ".", "upcase", "env", "[", "'rack.errors'", "]", "||=", "StringIO", ".", "new", "env", "[", "'faraday'", "]", "=", "faraday_env", "env", "end" ]
faraday to rack-compatible
[ "faraday", "to", "rack", "-", "compatible" ]
09b04ab68288205cc5579aaaf4138012f95268dd
https://github.com/lostisland/faraday_middleware/blob/09b04ab68288205cc5579aaaf4138012f95268dd/lib/faraday_middleware/rack_compatible.rb#L28-L42
14,656
lostisland/faraday_middleware
lib/faraday_middleware/rack_compatible.rb
FaradayMiddleware.RackCompatible.restore_env
def restore_env(rack_env) env = rack_env.fetch('faraday') headers = env[:request_headers] headers.clear rack_env.each do |name, value| next unless String === name && String === value if NonPrefixedHeaders.include? name or name.index('HTTP_') == 0 name = name.sub(/^HTTP_/, '').downcase.tr('_', '-') headers[name] = value end end env[:method] = rack_env['REQUEST_METHOD'].downcase.to_sym env[:rack_errors] = rack_env['rack.errors'] env end
ruby
def restore_env(rack_env) env = rack_env.fetch('faraday') headers = env[:request_headers] headers.clear rack_env.each do |name, value| next unless String === name && String === value if NonPrefixedHeaders.include? name or name.index('HTTP_') == 0 name = name.sub(/^HTTP_/, '').downcase.tr('_', '-') headers[name] = value end end env[:method] = rack_env['REQUEST_METHOD'].downcase.to_sym env[:rack_errors] = rack_env['rack.errors'] env end
[ "def", "restore_env", "(", "rack_env", ")", "env", "=", "rack_env", ".", "fetch", "(", "'faraday'", ")", "headers", "=", "env", "[", ":request_headers", "]", "headers", ".", "clear", "rack_env", ".", "each", "do", "|", "name", ",", "value", "|", "next", "unless", "String", "===", "name", "&&", "String", "===", "value", "if", "NonPrefixedHeaders", ".", "include?", "name", "or", "name", ".", "index", "(", "'HTTP_'", ")", "==", "0", "name", "=", "name", ".", "sub", "(", "/", "/", ",", "''", ")", ".", "downcase", ".", "tr", "(", "'_'", ",", "'-'", ")", "headers", "[", "name", "]", "=", "value", "end", "end", "env", "[", ":method", "]", "=", "rack_env", "[", "'REQUEST_METHOD'", "]", ".", "downcase", ".", "to_sym", "env", "[", ":rack_errors", "]", "=", "rack_env", "[", "'rack.errors'", "]", "env", "end" ]
rack to faraday-compatible
[ "rack", "to", "faraday", "-", "compatible" ]
09b04ab68288205cc5579aaaf4138012f95268dd
https://github.com/lostisland/faraday_middleware/blob/09b04ab68288205cc5579aaaf4138012f95268dd/lib/faraday_middleware/rack_compatible.rb#L55-L71
14,657
wincent/command-t
ruby/command-t/lib/command-t/match_window.rb
CommandT.MatchWindow.match_with_syntax_highlight
def match_with_syntax_highlight(match) highlight_chars = @prompt.abbrev.downcase.scan(/./mu) if @encoding && match.respond_to?(:force_encoding) && match.encoding != @encoding match = match.force_encoding(@encoding) end match.scan(/./mu).inject([]) do |output, char| if char.downcase == highlight_chars.first highlight_chars.shift output.concat [MH_START, char, MH_END] else output << char end end.join end
ruby
def match_with_syntax_highlight(match) highlight_chars = @prompt.abbrev.downcase.scan(/./mu) if @encoding && match.respond_to?(:force_encoding) && match.encoding != @encoding match = match.force_encoding(@encoding) end match.scan(/./mu).inject([]) do |output, char| if char.downcase == highlight_chars.first highlight_chars.shift output.concat [MH_START, char, MH_END] else output << char end end.join end
[ "def", "match_with_syntax_highlight", "(", "match", ")", "highlight_chars", "=", "@prompt", ".", "abbrev", ".", "downcase", ".", "scan", "(", "/", "/mu", ")", "if", "@encoding", "&&", "match", ".", "respond_to?", "(", ":force_encoding", ")", "&&", "match", ".", "encoding", "!=", "@encoding", "match", "=", "match", ".", "force_encoding", "(", "@encoding", ")", "end", "match", ".", "scan", "(", "/", "/mu", ")", ".", "inject", "(", "[", "]", ")", "do", "|", "output", ",", "char", "|", "if", "char", ".", "downcase", "==", "highlight_chars", ".", "first", "highlight_chars", ".", "shift", "output", ".", "concat", "[", "MH_START", ",", "char", ",", "MH_END", "]", "else", "output", "<<", "char", "end", "end", ".", "join", "end" ]
Highlight matching characters within the matched string. Note that this is only approximate; it will highlight the first matching instances within the string, which may not actually be the instances that were used by the matching/scoring algorithm to determine the best score for the match.
[ "Highlight", "matching", "characters", "within", "the", "matched", "string", "." ]
792d6079d32f1973c142c6fab89d2fdc94019ac8
https://github.com/wincent/command-t/blob/792d6079d32f1973c142c6fab89d2fdc94019ac8/ruby/command-t/lib/command-t/match_window.rb#L408-L423
14,658
wincent/command-t
ruby/command-t/lib/command-t/match_window.rb
CommandT.MatchWindow.print_match
def print_match(idx) return unless VIM::Window.select(@window) unlock @@buffer[line(idx)] = match_text_for_idx idx lock end
ruby
def print_match(idx) return unless VIM::Window.select(@window) unlock @@buffer[line(idx)] = match_text_for_idx idx lock end
[ "def", "print_match", "(", "idx", ")", "return", "unless", "VIM", "::", "Window", ".", "select", "(", "@window", ")", "unlock", "@@buffer", "[", "line", "(", "idx", ")", "]", "=", "match_text_for_idx", "idx", "lock", "end" ]
Print just the specified match.
[ "Print", "just", "the", "specified", "match", "." ]
792d6079d32f1973c142c6fab89d2fdc94019ac8
https://github.com/wincent/command-t/blob/792d6079d32f1973c142c6fab89d2fdc94019ac8/ruby/command-t/lib/command-t/match_window.rb#L426-L431
14,659
wincent/command-t
ruby/command-t/lib/command-t/match_window.rb
CommandT.MatchWindow.print_matches
def print_matches match_count = @matches.length if match_count == 0 print_error 'NO MATCHES' else return unless VIM::Window.select(@window) unlock clear @window_width = @window.width # update cached value desired_lines = [match_count, @min_height].max desired_lines = [max_lines, desired_lines].min @window.height = desired_lines matches = [] (0...@window.height).each do |idx| text = match_text_for_idx(idx) @reverse_list ? matches.unshift(text) : matches.push(text) end matches.each_with_index do |match, idx| if @@buffer.count > idx @@buffer[idx + 1] = match else @@buffer.append(idx, match) end end lock end end
ruby
def print_matches match_count = @matches.length if match_count == 0 print_error 'NO MATCHES' else return unless VIM::Window.select(@window) unlock clear @window_width = @window.width # update cached value desired_lines = [match_count, @min_height].max desired_lines = [max_lines, desired_lines].min @window.height = desired_lines matches = [] (0...@window.height).each do |idx| text = match_text_for_idx(idx) @reverse_list ? matches.unshift(text) : matches.push(text) end matches.each_with_index do |match, idx| if @@buffer.count > idx @@buffer[idx + 1] = match else @@buffer.append(idx, match) end end lock end end
[ "def", "print_matches", "match_count", "=", "@matches", ".", "length", "if", "match_count", "==", "0", "print_error", "'NO MATCHES'", "else", "return", "unless", "VIM", "::", "Window", ".", "select", "(", "@window", ")", "unlock", "clear", "@window_width", "=", "@window", ".", "width", "# update cached value", "desired_lines", "=", "[", "match_count", ",", "@min_height", "]", ".", "max", "desired_lines", "=", "[", "max_lines", ",", "desired_lines", "]", ".", "min", "@window", ".", "height", "=", "desired_lines", "matches", "=", "[", "]", "(", "0", "...", "@window", ".", "height", ")", ".", "each", "do", "|", "idx", "|", "text", "=", "match_text_for_idx", "(", "idx", ")", "@reverse_list", "?", "matches", ".", "unshift", "(", "text", ")", ":", "matches", ".", "push", "(", "text", ")", "end", "matches", ".", "each_with_index", "do", "|", "match", ",", "idx", "|", "if", "@@buffer", ".", "count", ">", "idx", "@@buffer", "[", "idx", "+", "1", "]", "=", "match", "else", "@@buffer", ".", "append", "(", "idx", ",", "match", ")", "end", "end", "lock", "end", "end" ]
Print all matches.
[ "Print", "all", "matches", "." ]
792d6079d32f1973c142c6fab89d2fdc94019ac8
https://github.com/wincent/command-t/blob/792d6079d32f1973c142c6fab89d2fdc94019ac8/ruby/command-t/lib/command-t/match_window.rb#L438-L464
14,660
wincent/command-t
ruby/command-t/lib/command-t/controller.rb
CommandT.Controller.quickfix
def quickfix hide matches = @matches.map do |match| "{ 'filename': '#{VIM::escape_for_single_quotes match}' }" end.join(', ') ::VIM::command 'call setqflist([' + matches + '])' ::VIM::command 'cope' end
ruby
def quickfix hide matches = @matches.map do |match| "{ 'filename': '#{VIM::escape_for_single_quotes match}' }" end.join(', ') ::VIM::command 'call setqflist([' + matches + '])' ::VIM::command 'cope' end
[ "def", "quickfix", "hide", "matches", "=", "@matches", ".", "map", "do", "|", "match", "|", "\"{ 'filename': '#{VIM::escape_for_single_quotes match}' }\"", "end", ".", "join", "(", "', '", ")", "::", "VIM", "::", "command", "'call setqflist(['", "+", "matches", "+", "'])'", "::", "VIM", "::", "command", "'cope'", "end" ]
Take current matches and stick them in the quickfix window.
[ "Take", "current", "matches", "and", "stick", "them", "in", "the", "quickfix", "window", "." ]
792d6079d32f1973c142c6fab89d2fdc94019ac8
https://github.com/wincent/command-t/blob/792d6079d32f1973c142c6fab89d2fdc94019ac8/ruby/command-t/lib/command-t/controller.rb#L168-L177
14,661
wincent/command-t
ruby/command-t/lib/command-t/prompt.rb
CommandT.Prompt.backspace!
def backspace! if @col > 0 left, cursor, right = abbrev_segments @abbrev = left.chop! + cursor + right @col -= 1 redraw end end
ruby
def backspace! if @col > 0 left, cursor, right = abbrev_segments @abbrev = left.chop! + cursor + right @col -= 1 redraw end end
[ "def", "backspace!", "if", "@col", ">", "0", "left", ",", "cursor", ",", "right", "=", "abbrev_segments", "@abbrev", "=", "left", ".", "chop!", "+", "cursor", "+", "right", "@col", "-=", "1", "redraw", "end", "end" ]
Delete a character to the left of the current cursor position.
[ "Delete", "a", "character", "to", "the", "left", "of", "the", "current", "cursor", "position", "." ]
792d6079d32f1973c142c6fab89d2fdc94019ac8
https://github.com/wincent/command-t/blob/792d6079d32f1973c142c6fab89d2fdc94019ac8/ruby/command-t/lib/command-t/prompt.rb#L56-L63
14,662
afair/email_address
lib/email_address/local.rb
EmailAddress.Local.format
def format(form=@config[:local_format]||:conventional) if @config[:local_format].is_a?(Proc) @config[:local_format].call(self) elsif form == :conventional self.conventional elsif form == :canonical self.canonical elsif form == :relaxed self.relax elsif form == :standard self.standard end end
ruby
def format(form=@config[:local_format]||:conventional) if @config[:local_format].is_a?(Proc) @config[:local_format].call(self) elsif form == :conventional self.conventional elsif form == :canonical self.canonical elsif form == :relaxed self.relax elsif form == :standard self.standard end end
[ "def", "format", "(", "form", "=", "@config", "[", ":local_format", "]", "||", ":conventional", ")", "if", "@config", "[", ":local_format", "]", ".", "is_a?", "(", "Proc", ")", "@config", "[", ":local_format", "]", ".", "call", "(", "self", ")", "elsif", "form", "==", ":conventional", "self", ".", "conventional", "elsif", "form", "==", ":canonical", "self", ".", "canonical", "elsif", "form", "==", ":relaxed", "self", ".", "relax", "elsif", "form", "==", ":standard", "self", ".", "standard", "end", "end" ]
Builds the local string according to configurations
[ "Builds", "the", "local", "string", "according", "to", "configurations" ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/local.rb#L188-L200
14,663
afair/email_address
lib/email_address/local.rb
EmailAddress.Local.standard
def standard form = self.mailbox form += @config[:tag_separator] + self.tag if self.tag form += "(" + self.comment + ")" if self.comment form.gsub!(/([\\\"])/, '\\\1') # Escape \ and " if form =~ /[ \"\(\),:<>@\[\\\]]/ # Space and "(),:;<>@[\] form = %Q("#{form}") end form end
ruby
def standard form = self.mailbox form += @config[:tag_separator] + self.tag if self.tag form += "(" + self.comment + ")" if self.comment form.gsub!(/([\\\"])/, '\\\1') # Escape \ and " if form =~ /[ \"\(\),:<>@\[\\\]]/ # Space and "(),:;<>@[\] form = %Q("#{form}") end form end
[ "def", "standard", "form", "=", "self", ".", "mailbox", "form", "+=", "@config", "[", ":tag_separator", "]", "+", "self", ".", "tag", "if", "self", ".", "tag", "form", "+=", "\"(\"", "+", "self", ".", "comment", "+", "\")\"", "if", "self", ".", "comment", "form", ".", "gsub!", "(", "/", "\\\\", "\\\"", "/", ",", "'\\\\\\1'", ")", "# Escape \\ and \"", "if", "form", "=~", "/", "\\\"", "\\(", "\\)", "\\[", "\\\\", "\\]", "/", "# Space and \"(),:;<>@[\\]", "form", "=", "%Q(\"#{form}\")", "end", "form", "end" ]
Returns a normalized version of the standard address parts.
[ "Returns", "a", "normalized", "version", "of", "the", "standard", "address", "parts", "." ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/local.rb#L229-L238
14,664
afair/email_address
lib/email_address/local.rb
EmailAddress.Local.conventional?
def conventional? self.syntax = :invalid self.local =~ CONVENTIONAL_MAILBOX_REGEX or return false self.valid_size? or return false self.valid_encoding? or return false self.syntax = :conventional true end
ruby
def conventional? self.syntax = :invalid self.local =~ CONVENTIONAL_MAILBOX_REGEX or return false self.valid_size? or return false self.valid_encoding? or return false self.syntax = :conventional true end
[ "def", "conventional?", "self", ".", "syntax", "=", ":invalid", "self", ".", "local", "=~", "CONVENTIONAL_MAILBOX_REGEX", "or", "return", "false", "self", ".", "valid_size?", "or", "return", "false", "self", ".", "valid_encoding?", "or", "return", "false", "self", ".", "syntax", "=", ":conventional", "true", "end" ]
True if the part matches the conventional format
[ "True", "if", "the", "part", "matches", "the", "conventional", "format" ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/local.rb#L329-L336
14,665
afair/email_address
lib/email_address/local.rb
EmailAddress.Local.relaxed?
def relaxed? self.syntax = :invalid self.valid_size? or return false self.valid_encoding? or return false if self.local =~ RELAXED_MAILBOX_REGEX self.syntax = :relaxed true else false end end
ruby
def relaxed? self.syntax = :invalid self.valid_size? or return false self.valid_encoding? or return false if self.local =~ RELAXED_MAILBOX_REGEX self.syntax = :relaxed true else false end end
[ "def", "relaxed?", "self", ".", "syntax", "=", ":invalid", "self", ".", "valid_size?", "or", "return", "false", "self", ".", "valid_encoding?", "or", "return", "false", "if", "self", ".", "local", "=~", "RELAXED_MAILBOX_REGEX", "self", ".", "syntax", "=", ":relaxed", "true", "else", "false", "end", "end" ]
Relaxed conventional is not so strict about character order.
[ "Relaxed", "conventional", "is", "not", "so", "strict", "about", "character", "order", "." ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/local.rb#L339-L349
14,666
afair/email_address
lib/email_address/local.rb
EmailAddress.Local.standard?
def standard? self.syntax = :invalid self.valid_size? or return false self.valid_encoding? or return false if self.local =~ STANDARD_LOCAL_REGEX self.syntax = :standard true else false end end
ruby
def standard? self.syntax = :invalid self.valid_size? or return false self.valid_encoding? or return false if self.local =~ STANDARD_LOCAL_REGEX self.syntax = :standard true else false end end
[ "def", "standard?", "self", ".", "syntax", "=", ":invalid", "self", ".", "valid_size?", "or", "return", "false", "self", ".", "valid_encoding?", "or", "return", "false", "if", "self", ".", "local", "=~", "STANDARD_LOCAL_REGEX", "self", ".", "syntax", "=", ":standard", "true", "else", "false", "end", "end" ]
True if the part matches the RFC standard format
[ "True", "if", "the", "part", "matches", "the", "RFC", "standard", "format" ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/local.rb#L352-L362
14,667
afair/email_address
lib/email_address/local.rb
EmailAddress.Local.matches?
def matches?(*rules) rules.flatten.each do |r| if r =~ /(.+)@\z/ return r if File.fnmatch?($1, self.local) end end false end
ruby
def matches?(*rules) rules.flatten.each do |r| if r =~ /(.+)@\z/ return r if File.fnmatch?($1, self.local) end end false end
[ "def", "matches?", "(", "*", "rules", ")", "rules", ".", "flatten", ".", "each", "do", "|", "r", "|", "if", "r", "=~", "/", "\\z", "/", "return", "r", "if", "File", ".", "fnmatch?", "(", "$1", ",", "self", ".", "local", ")", "end", "end", "false", "end" ]
Matches configured formated form against File glob strings given. Rules must end in @ to distinguish themselves from other email part matches.
[ "Matches", "configured", "formated", "form", "against", "File", "glob", "strings", "given", ".", "Rules", "must", "end", "in" ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/local.rb#L366-L373
14,668
afair/email_address
lib/email_address/address.rb
EmailAddress.Address.canonical
def canonical c = self.local.canonical c += "@" + self.host.canonical if self.host.canonical && self.host.canonical > " " c end
ruby
def canonical c = self.local.canonical c += "@" + self.host.canonical if self.host.canonical && self.host.canonical > " " c end
[ "def", "canonical", "c", "=", "self", ".", "local", ".", "canonical", "c", "+=", "\"@\"", "+", "self", ".", "host", ".", "canonical", "if", "self", ".", "host", ".", "canonical", "&&", "self", ".", "host", ".", "canonical", ">", "\" \"", "c", "end" ]
Returns the canonical email address according to the provider uniqueness rules. Usually, this downcases the address, removes spaves and comments and tags, and any extraneous part of the address not considered a unique account by the provider.
[ "Returns", "the", "canonical", "email", "address", "according", "to", "the", "provider", "uniqueness", "rules", ".", "Usually", "this", "downcases", "the", "address", "removes", "spaves", "and", "comments", "and", "tags", "and", "any", "extraneous", "part", "of", "the", "address", "not", "considered", "a", "unique", "account", "by", "the", "provider", "." ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/address.rb#L125-L129
14,669
afair/email_address
lib/email_address/exchanger.rb
EmailAddress.Exchanger.provider
def provider return @provider if defined? @provider EmailAddress::Config.providers.each do |provider, config| if config[:exchanger_match] && self.matches?(config[:exchanger_match]) return @provider = provider end end @provider = :default end
ruby
def provider return @provider if defined? @provider EmailAddress::Config.providers.each do |provider, config| if config[:exchanger_match] && self.matches?(config[:exchanger_match]) return @provider = provider end end @provider = :default end
[ "def", "provider", "return", "@provider", "if", "defined?", "@provider", "EmailAddress", "::", "Config", ".", "providers", ".", "each", "do", "|", "provider", ",", "config", "|", "if", "config", "[", ":exchanger_match", "]", "&&", "self", ".", "matches?", "(", "config", "[", ":exchanger_match", "]", ")", "return", "@provider", "=", "provider", "end", "end", "@provider", "=", ":default", "end" ]
Returns the provider name based on the MX-er host names, or nil if not matched
[ "Returns", "the", "provider", "name", "based", "on", "the", "MX", "-", "er", "host", "names", "or", "nil", "if", "not", "matched" ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/exchanger.rb#L37-L45
14,670
afair/email_address
lib/email_address/exchanger.rb
EmailAddress.Exchanger.domains
def domains @_domains ||= mxers.map {|m| EmailAddress::Host.new(m.first).domain_name }.sort.uniq end
ruby
def domains @_domains ||= mxers.map {|m| EmailAddress::Host.new(m.first).domain_name }.sort.uniq end
[ "def", "domains", "@_domains", "||=", "mxers", ".", "map", "{", "|", "m", "|", "EmailAddress", "::", "Host", ".", "new", "(", "m", ".", "first", ")", ".", "domain_name", "}", ".", "sort", ".", "uniq", "end" ]
Returns Array of domain names for the MX'ers, used to determine the Provider
[ "Returns", "Array", "of", "domain", "names", "for", "the", "MX", "ers", "used", "to", "determine", "the", "Provider" ]
6c720b37061a52a92e84db90df0a8b5eef3de39a
https://github.com/afair/email_address/blob/6c720b37061a52a92e84db90df0a8b5eef3de39a/lib/email_address/exchanger.rb#L72-L74
14,671
openzipkin/zipkin-ruby
lib/zipkin-tracer/hostname_resolver.rb
ZipkinTracer.HostnameResolver.unique_hosts
def unique_hosts(spans) hosts = [] each_endpoint(spans) do |endpoint| hosts.push(endpoint) end hosts.uniq end
ruby
def unique_hosts(spans) hosts = [] each_endpoint(spans) do |endpoint| hosts.push(endpoint) end hosts.uniq end
[ "def", "unique_hosts", "(", "spans", ")", "hosts", "=", "[", "]", "each_endpoint", "(", "spans", ")", "do", "|", "endpoint", "|", "hosts", ".", "push", "(", "endpoint", ")", "end", "hosts", ".", "uniq", "end" ]
Using this to resolve only once per host
[ "Using", "this", "to", "resolve", "only", "once", "per", "host" ]
ce914d2fd9993fe898ba373595d9d43cd03c4e03
https://github.com/openzipkin/zipkin-ruby/blob/ce914d2fd9993fe898ba373595d9d43cd03c4e03/lib/zipkin-tracer/hostname_resolver.rb#L43-L49
14,672
zendesk/delivery_boy
lib/delivery_boy/instance.rb
DeliveryBoy.Instance.producer_options
def producer_options { required_acks: config.required_acks, ack_timeout: config.ack_timeout, max_retries: config.max_retries, retry_backoff: config.retry_backoff, max_buffer_size: config.max_buffer_size, max_buffer_bytesize: config.max_buffer_bytesize, compression_codec: (config.compression_codec.to_sym if config.compression_codec), compression_threshold: config.compression_threshold, } end
ruby
def producer_options { required_acks: config.required_acks, ack_timeout: config.ack_timeout, max_retries: config.max_retries, retry_backoff: config.retry_backoff, max_buffer_size: config.max_buffer_size, max_buffer_bytesize: config.max_buffer_bytesize, compression_codec: (config.compression_codec.to_sym if config.compression_codec), compression_threshold: config.compression_threshold, } end
[ "def", "producer_options", "{", "required_acks", ":", "config", ".", "required_acks", ",", "ack_timeout", ":", "config", ".", "ack_timeout", ",", "max_retries", ":", "config", ".", "max_retries", ",", "retry_backoff", ":", "config", ".", "retry_backoff", ",", "max_buffer_size", ":", "config", ".", "max_buffer_size", ",", "max_buffer_bytesize", ":", "config", ".", "max_buffer_bytesize", ",", "compression_codec", ":", "(", "config", ".", "compression_codec", ".", "to_sym", "if", "config", ".", "compression_codec", ")", ",", "compression_threshold", ":", "config", ".", "compression_threshold", ",", "}", "end" ]
Options for both the sync and async producers.
[ "Options", "for", "both", "the", "sync", "and", "async", "producers", "." ]
077e9e451267e1a64aa25733e08ff36ff4e7f2f4
https://github.com/zendesk/delivery_boy/blob/077e9e451267e1a64aa25733e08ff36ff4e7f2f4/lib/delivery_boy/instance.rb#L85-L96
14,673
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.get_schedule
def get_schedule(name = nil) if name.nil? get_all_schedules else encoded_schedule = SidekiqScheduler::RedisManager.get_job_schedule(name) encoded_schedule.nil? ? nil : JSON.parse(encoded_schedule) end end
ruby
def get_schedule(name = nil) if name.nil? get_all_schedules else encoded_schedule = SidekiqScheduler::RedisManager.get_job_schedule(name) encoded_schedule.nil? ? nil : JSON.parse(encoded_schedule) end end
[ "def", "get_schedule", "(", "name", "=", "nil", ")", "if", "name", ".", "nil?", "get_all_schedules", "else", "encoded_schedule", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_schedule", "(", "name", ")", "encoded_schedule", ".", "nil?", "?", "nil", ":", "JSON", ".", "parse", "(", "encoded_schedule", ")", "end", "end" ]
Retrive the schedule configuration for the given name if the name is nil it returns a hash with all the names end their schedules.
[ "Retrive", "the", "schedule", "configuration", "for", "the", "given", "name", "if", "the", "name", "is", "nil", "it", "returns", "a", "hash", "with", "all", "the", "names", "end", "their", "schedules", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L71-L78
14,674
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.get_all_schedules
def get_all_schedules schedules = {} if SidekiqScheduler::RedisManager.schedule_exist? SidekiqScheduler::RedisManager.get_all_schedules.tap do |h| h.each do |name, config| schedules[name] = JSON.parse(config) end end end schedules end
ruby
def get_all_schedules schedules = {} if SidekiqScheduler::RedisManager.schedule_exist? SidekiqScheduler::RedisManager.get_all_schedules.tap do |h| h.each do |name, config| schedules[name] = JSON.parse(config) end end end schedules end
[ "def", "get_all_schedules", "schedules", "=", "{", "}", "if", "SidekiqScheduler", "::", "RedisManager", ".", "schedule_exist?", "SidekiqScheduler", "::", "RedisManager", ".", "get_all_schedules", ".", "tap", "do", "|", "h", "|", "h", ".", "each", "do", "|", "name", ",", "config", "|", "schedules", "[", "name", "]", "=", "JSON", ".", "parse", "(", "config", ")", "end", "end", "end", "schedules", "end" ]
gets the schedule as it exists in redis
[ "gets", "the", "schedule", "as", "it", "exists", "in", "redis" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L81-L93
14,675
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.set_schedule
def set_schedule(name, config) existing_config = get_schedule(name) unless existing_config && existing_config == config SidekiqScheduler::RedisManager.set_job_schedule(name, config) SidekiqScheduler::RedisManager.add_schedule_change(name) end config end
ruby
def set_schedule(name, config) existing_config = get_schedule(name) unless existing_config && existing_config == config SidekiqScheduler::RedisManager.set_job_schedule(name, config) SidekiqScheduler::RedisManager.add_schedule_change(name) end config end
[ "def", "set_schedule", "(", "name", ",", "config", ")", "existing_config", "=", "get_schedule", "(", "name", ")", "unless", "existing_config", "&&", "existing_config", "==", "config", "SidekiqScheduler", "::", "RedisManager", ".", "set_job_schedule", "(", "name", ",", "config", ")", "SidekiqScheduler", "::", "RedisManager", ".", "add_schedule_change", "(", "name", ")", "end", "config", "end" ]
Create or update a schedule with the provided name and configuration. Note: values for class and custom_job_class need to be strings, not constants. Sidekiq.set_schedule('some_job', { :class => 'SomeJob', :every => '15mins', :queue => 'high', :args => '/tmp/poop' })
[ "Create", "or", "update", "a", "schedule", "with", "the", "provided", "name", "and", "configuration", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L104-L111
14,676
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/schedule.rb
SidekiqScheduler.Schedule.remove_schedule
def remove_schedule(name) SidekiqScheduler::RedisManager.remove_job_schedule(name) SidekiqScheduler::RedisManager.add_schedule_change(name) end
ruby
def remove_schedule(name) SidekiqScheduler::RedisManager.remove_job_schedule(name) SidekiqScheduler::RedisManager.add_schedule_change(name) end
[ "def", "remove_schedule", "(", "name", ")", "SidekiqScheduler", "::", "RedisManager", ".", "remove_job_schedule", "(", "name", ")", "SidekiqScheduler", "::", "RedisManager", ".", "add_schedule_change", "(", "name", ")", "end" ]
remove a given schedule by name
[ "remove", "a", "given", "schedule", "by", "name" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/schedule.rb#L114-L117
14,677
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.load_schedule!
def load_schedule! if enabled Sidekiq.logger.info 'Loading Schedule' # Load schedule from redis for the first time if dynamic if dynamic Sidekiq.reload_schedule! @current_changed_score = Time.now.to_f rufus_scheduler.every(dynamic_every) do update_schedule end end Sidekiq.logger.info 'Schedule empty! Set Sidekiq.schedule' if Sidekiq.schedule.empty? @scheduled_jobs = {} queues = sidekiq_queues Sidekiq.schedule.each do |name, config| if !listened_queues_only || enabled_queue?(config['queue'].to_s, queues) load_schedule_job(name, config) else Sidekiq.logger.info { "Ignoring #{name}, job's queue is not enabled." } end end Sidekiq.logger.info 'Schedules Loaded' else Sidekiq.logger.info 'SidekiqScheduler is disabled' end end
ruby
def load_schedule! if enabled Sidekiq.logger.info 'Loading Schedule' # Load schedule from redis for the first time if dynamic if dynamic Sidekiq.reload_schedule! @current_changed_score = Time.now.to_f rufus_scheduler.every(dynamic_every) do update_schedule end end Sidekiq.logger.info 'Schedule empty! Set Sidekiq.schedule' if Sidekiq.schedule.empty? @scheduled_jobs = {} queues = sidekiq_queues Sidekiq.schedule.each do |name, config| if !listened_queues_only || enabled_queue?(config['queue'].to_s, queues) load_schedule_job(name, config) else Sidekiq.logger.info { "Ignoring #{name}, job's queue is not enabled." } end end Sidekiq.logger.info 'Schedules Loaded' else Sidekiq.logger.info 'SidekiqScheduler is disabled' end end
[ "def", "load_schedule!", "if", "enabled", "Sidekiq", ".", "logger", ".", "info", "'Loading Schedule'", "# Load schedule from redis for the first time if dynamic", "if", "dynamic", "Sidekiq", ".", "reload_schedule!", "@current_changed_score", "=", "Time", ".", "now", ".", "to_f", "rufus_scheduler", ".", "every", "(", "dynamic_every", ")", "do", "update_schedule", "end", "end", "Sidekiq", ".", "logger", ".", "info", "'Schedule empty! Set Sidekiq.schedule'", "if", "Sidekiq", ".", "schedule", ".", "empty?", "@scheduled_jobs", "=", "{", "}", "queues", "=", "sidekiq_queues", "Sidekiq", ".", "schedule", ".", "each", "do", "|", "name", ",", "config", "|", "if", "!", "listened_queues_only", "||", "enabled_queue?", "(", "config", "[", "'queue'", "]", ".", "to_s", ",", "queues", ")", "load_schedule_job", "(", "name", ",", "config", ")", "else", "Sidekiq", ".", "logger", ".", "info", "{", "\"Ignoring #{name}, job's queue is not enabled.\"", "}", "end", "end", "Sidekiq", ".", "logger", ".", "info", "'Schedules Loaded'", "else", "Sidekiq", ".", "logger", ".", "info", "'SidekiqScheduler is disabled'", "end", "end" ]
Pulls the schedule from Sidekiq.schedule and loads it into the rufus scheduler instance
[ "Pulls", "the", "schedule", "from", "Sidekiq", ".", "schedule", "and", "loads", "it", "into", "the", "rufus", "scheduler", "instance" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L70-L100
14,678
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.idempotent_job_enqueue
def idempotent_job_enqueue(job_name, time, config) registered = SidekiqScheduler::RedisManager.register_job_instance(job_name, time) if registered Sidekiq.logger.info "queueing #{config['class']} (#{job_name})" handle_errors { enqueue_job(config, time) } SidekiqScheduler::RedisManager.remove_elder_job_instances(job_name) else Sidekiq.logger.debug { "Ignoring #{job_name} job as it has been already enqueued" } end end
ruby
def idempotent_job_enqueue(job_name, time, config) registered = SidekiqScheduler::RedisManager.register_job_instance(job_name, time) if registered Sidekiq.logger.info "queueing #{config['class']} (#{job_name})" handle_errors { enqueue_job(config, time) } SidekiqScheduler::RedisManager.remove_elder_job_instances(job_name) else Sidekiq.logger.debug { "Ignoring #{job_name} job as it has been already enqueued" } end end
[ "def", "idempotent_job_enqueue", "(", "job_name", ",", "time", ",", "config", ")", "registered", "=", "SidekiqScheduler", "::", "RedisManager", ".", "register_job_instance", "(", "job_name", ",", "time", ")", "if", "registered", "Sidekiq", ".", "logger", ".", "info", "\"queueing #{config['class']} (#{job_name})\"", "handle_errors", "{", "enqueue_job", "(", "config", ",", "time", ")", "}", "SidekiqScheduler", "::", "RedisManager", ".", "remove_elder_job_instances", "(", "job_name", ")", "else", "Sidekiq", ".", "logger", ".", "debug", "{", "\"Ignoring #{job_name} job as it has been already enqueued\"", "}", "end", "end" ]
Pushes the job into Sidekiq if not already pushed for the given time @param [String] job_name The job's name @param [Time] time The time when the job got cleared for triggering @param [Hash] config Job's config hash
[ "Pushes", "the", "job", "into", "Sidekiq", "if", "not", "already", "pushed", "for", "the", "given", "time" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L140-L152
14,679
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.enqueue_job
def enqueue_job(job_config, time = Time.now) config = prepare_arguments(job_config.dup) if config.delete('include_metadata') config['args'] = arguments_with_metadata(config['args'], scheduled_at: time.to_f) end if active_job_enqueue?(config['class']) SidekiqScheduler::Utils.enqueue_with_active_job(config) else SidekiqScheduler::Utils.enqueue_with_sidekiq(config) end end
ruby
def enqueue_job(job_config, time = Time.now) config = prepare_arguments(job_config.dup) if config.delete('include_metadata') config['args'] = arguments_with_metadata(config['args'], scheduled_at: time.to_f) end if active_job_enqueue?(config['class']) SidekiqScheduler::Utils.enqueue_with_active_job(config) else SidekiqScheduler::Utils.enqueue_with_sidekiq(config) end end
[ "def", "enqueue_job", "(", "job_config", ",", "time", "=", "Time", ".", "now", ")", "config", "=", "prepare_arguments", "(", "job_config", ".", "dup", ")", "if", "config", ".", "delete", "(", "'include_metadata'", ")", "config", "[", "'args'", "]", "=", "arguments_with_metadata", "(", "config", "[", "'args'", "]", ",", "scheduled_at", ":", "time", ".", "to_f", ")", "end", "if", "active_job_enqueue?", "(", "config", "[", "'class'", "]", ")", "SidekiqScheduler", "::", "Utils", ".", "enqueue_with_active_job", "(", "config", ")", "else", "SidekiqScheduler", "::", "Utils", ".", "enqueue_with_sidekiq", "(", "config", ")", "end", "end" ]
Enqueue a job based on a config hash @param job_config [Hash] the job configuration @param time [Time] time the job is enqueued
[ "Enqueue", "a", "job", "based", "on", "a", "config", "hash" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L158-L170
14,680
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.schedule_state
def schedule_state(name) state = SidekiqScheduler::RedisManager.get_job_state(name) state ? JSON.parse(state) : {} end
ruby
def schedule_state(name) state = SidekiqScheduler::RedisManager.get_job_state(name) state ? JSON.parse(state) : {} end
[ "def", "schedule_state", "(", "name", ")", "state", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_state", "(", "name", ")", "state", "?", "JSON", ".", "parse", "(", "state", ")", ":", "{", "}", "end" ]
Retrieves a schedule state @param name [String] with the schedule's name @return [Hash] with the schedule's state
[ "Retrieves", "a", "schedule", "state" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L262-L266
14,681
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.arguments_with_metadata
def arguments_with_metadata(args, metadata) if args.is_a? Array [*args, metadata] else [args, metadata] end end
ruby
def arguments_with_metadata(args, metadata) if args.is_a? Array [*args, metadata] else [args, metadata] end end
[ "def", "arguments_with_metadata", "(", "args", ",", "metadata", ")", "if", "args", ".", "is_a?", "Array", "[", "args", ",", "metadata", "]", "else", "[", "args", ",", "metadata", "]", "end", "end" ]
Adds a Hash with schedule metadata as the last argument to call the worker. It currently returns the schedule time as a Float number representing the milisencods since epoch. @example with hash argument arguments_with_metadata({value: 1}, scheduled_at: Time.now) #=> [{value: 1}, {scheduled_at: <miliseconds since epoch>}] @param args [Array|Hash] @param metadata [Hash] @return [Array] arguments with added metadata
[ "Adds", "a", "Hash", "with", "schedule", "metadata", "as", "the", "last", "argument", "to", "call", "the", "worker", ".", "It", "currently", "returns", "the", "schedule", "time", "as", "a", "Float", "number", "representing", "the", "milisencods", "since", "epoch", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L287-L293
14,682
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.active_job_enqueue?
def active_job_enqueue?(klass) klass.is_a?(Class) && defined?(ActiveJob::Enqueuing) && klass.included_modules.include?(ActiveJob::Enqueuing) end
ruby
def active_job_enqueue?(klass) klass.is_a?(Class) && defined?(ActiveJob::Enqueuing) && klass.included_modules.include?(ActiveJob::Enqueuing) end
[ "def", "active_job_enqueue?", "(", "klass", ")", "klass", ".", "is_a?", "(", "Class", ")", "&&", "defined?", "(", "ActiveJob", "::", "Enqueuing", ")", "&&", "klass", ".", "included_modules", ".", "include?", "(", "ActiveJob", "::", "Enqueuing", ")", "end" ]
Returns true if the enqueuing needs to be done for an ActiveJob class false otherwise. @param [Class] klass the class to check is decendant from ActiveJob @return [Boolean]
[ "Returns", "true", "if", "the", "enqueuing", "needs", "to", "be", "done", "for", "an", "ActiveJob", "class", "false", "otherwise", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L317-L320
14,683
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/scheduler.rb
SidekiqScheduler.Scheduler.prepare_arguments
def prepare_arguments(config) config['class'] = SidekiqScheduler::Utils.try_to_constantize(config['class']) if config['args'].is_a?(Hash) config['args'].symbolize_keys! if config['args'].respond_to?(:symbolize_keys!) else config['args'] = Array(config['args']) end config end
ruby
def prepare_arguments(config) config['class'] = SidekiqScheduler::Utils.try_to_constantize(config['class']) if config['args'].is_a?(Hash) config['args'].symbolize_keys! if config['args'].respond_to?(:symbolize_keys!) else config['args'] = Array(config['args']) end config end
[ "def", "prepare_arguments", "(", "config", ")", "config", "[", "'class'", "]", "=", "SidekiqScheduler", "::", "Utils", ".", "try_to_constantize", "(", "config", "[", "'class'", "]", ")", "if", "config", "[", "'args'", "]", ".", "is_a?", "(", "Hash", ")", "config", "[", "'args'", "]", ".", "symbolize_keys!", "if", "config", "[", "'args'", "]", ".", "respond_to?", "(", ":symbolize_keys!", ")", "else", "config", "[", "'args'", "]", "=", "Array", "(", "config", "[", "'args'", "]", ")", "end", "config", "end" ]
Convert the given arguments in the format expected to be enqueued. @param [Hash] config the options to be converted @option config [String] class the job class @option config [Hash/Array] args the arguments to be passed to the job class @return [Hash]
[ "Convert", "the", "given", "arguments", "in", "the", "format", "expected", "to", "be", "enqueued", "." ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/scheduler.rb#L330-L340
14,684
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/job_presenter.rb
SidekiqScheduler.JobPresenter.next_time
def next_time execution_time = SidekiqScheduler::RedisManager.get_job_next_time(name) relative_time(Time.parse(execution_time)) if execution_time end
ruby
def next_time execution_time = SidekiqScheduler::RedisManager.get_job_next_time(name) relative_time(Time.parse(execution_time)) if execution_time end
[ "def", "next_time", "execution_time", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_next_time", "(", "name", ")", "relative_time", "(", "Time", ".", "parse", "(", "execution_time", ")", ")", "if", "execution_time", "end" ]
Returns the next time execution for the job @return [String] with the job's next time
[ "Returns", "the", "next", "time", "execution", "for", "the", "job" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/job_presenter.rb#L22-L26
14,685
moove-it/sidekiq-scheduler
lib/sidekiq-scheduler/job_presenter.rb
SidekiqScheduler.JobPresenter.last_time
def last_time execution_time = SidekiqScheduler::RedisManager.get_job_last_time(name) relative_time(Time.parse(execution_time)) if execution_time end
ruby
def last_time execution_time = SidekiqScheduler::RedisManager.get_job_last_time(name) relative_time(Time.parse(execution_time)) if execution_time end
[ "def", "last_time", "execution_time", "=", "SidekiqScheduler", "::", "RedisManager", ".", "get_job_last_time", "(", "name", ")", "relative_time", "(", "Time", ".", "parse", "(", "execution_time", ")", ")", "if", "execution_time", "end" ]
Returns the last execution time for the job @return [String] with the job's last time
[ "Returns", "the", "last", "execution", "time", "for", "the", "job" ]
25d3406044196dfb58d74caac920c9a2991eb486
https://github.com/moove-it/sidekiq-scheduler/blob/25d3406044196dfb58d74caac920c9a2991eb486/lib/sidekiq-scheduler/job_presenter.rb#L31-L35
14,686
stitchfix/stitches
lib/stitches/deprecation.rb
Stitches.Deprecation.deprecated
def deprecated(gone_on:,&block) response.set_header("Sunset",Date.parse(gone_on).in_time_zone("GMT").midnight.strftime("%a, %e %b %Y %H:%M:%S %Z")) Rails.logger.info("DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}") block.() end
ruby
def deprecated(gone_on:,&block) response.set_header("Sunset",Date.parse(gone_on).in_time_zone("GMT").midnight.strftime("%a, %e %b %Y %H:%M:%S %Z")) Rails.logger.info("DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}") block.() end
[ "def", "deprecated", "(", "gone_on", ":", ",", "&", "block", ")", "response", ".", "set_header", "(", "\"Sunset\"", ",", "Date", ".", "parse", "(", "gone_on", ")", ".", "in_time_zone", "(", "\"GMT\"", ")", ".", "midnight", ".", "strftime", "(", "\"%a, %e %b %Y %H:%M:%S %Z\"", ")", ")", "Rails", ".", "logger", ".", "info", "(", "\"DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}\"", ")", "block", ".", "(", ")", "end" ]
Indicate that this endpoint is deprecated and will go away on the given date. gon_on: - date, as a string, when this endpoint will go away block - the contents of the endpoint Example: def show deprecated gone_on: "2019-04-09" do render widgets: { Widget.find(params[:id]) } end end
[ "Indicate", "that", "this", "endpoint", "is", "deprecated", "and", "will", "go", "away", "on", "the", "given", "date", "." ]
80231b33db26b2e82d13e2794c448beb21169527
https://github.com/stitchfix/stitches/blob/80231b33db26b2e82d13e2794c448beb21169527/lib/stitches/deprecation.rb#L20-L24
14,687
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.align_column
def align_column n, alignment r = rows column(n).each_with_index do |col, i| cell = r[i][n] next unless cell cell.alignment = alignment unless cell.alignment? end end
ruby
def align_column n, alignment r = rows column(n).each_with_index do |col, i| cell = r[i][n] next unless cell cell.alignment = alignment unless cell.alignment? end end
[ "def", "align_column", "n", ",", "alignment", "r", "=", "rows", "column", "(", "n", ")", ".", "each_with_index", "do", "|", "col", ",", "i", "|", "cell", "=", "r", "[", "i", "]", "[", "n", "]", "next", "unless", "cell", "cell", ".", "alignment", "=", "alignment", "unless", "cell", ".", "alignment?", "end", "end" ]
Generates a ASCII table with the given _options_. Align column _n_ to the given _alignment_ of :center, :left, or :right.
[ "Generates", "a", "ASCII", "table", "with", "the", "given", "_options_", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L28-L35
14,688
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.add_row
def add_row array row = array == :separator ? Separator.new(self) : Row.new(self, array) @rows << row require_column_widths_recalc unless row.is_a?(Separator) end
ruby
def add_row array row = array == :separator ? Separator.new(self) : Row.new(self, array) @rows << row require_column_widths_recalc unless row.is_a?(Separator) end
[ "def", "add_row", "array", "row", "=", "array", "==", ":separator", "?", "Separator", ".", "new", "(", "self", ")", ":", "Row", ".", "new", "(", "self", ",", "array", ")", "@rows", "<<", "row", "require_column_widths_recalc", "unless", "row", ".", "is_a?", "(", "Separator", ")", "end" ]
Add a row.
[ "Add", "a", "row", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L40-L44
14,689
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.column
def column n, method = :value, array = rows array.map { |row| # for each cells in a row, find the column with index # just greater than the required one, and go back one. index = col = 0 row.cells.each do |cell| break if index > n index += cell.colspan col += 1 end cell = row[col - 1] cell && method ? cell.__send__(method) : cell }.compact end
ruby
def column n, method = :value, array = rows array.map { |row| # for each cells in a row, find the column with index # just greater than the required one, and go back one. index = col = 0 row.cells.each do |cell| break if index > n index += cell.colspan col += 1 end cell = row[col - 1] cell && method ? cell.__send__(method) : cell }.compact end
[ "def", "column", "n", ",", "method", "=", ":value", ",", "array", "=", "rows", "array", ".", "map", "{", "|", "row", "|", "# for each cells in a row, find the column with index", "# just greater than the required one, and go back one.", "index", "=", "col", "=", "0", "row", ".", "cells", ".", "each", "do", "|", "cell", "|", "break", "if", "index", ">", "n", "index", "+=", "cell", ".", "colspan", "col", "+=", "1", "end", "cell", "=", "row", "[", "col", "-", "1", "]", "cell", "&&", "method", "?", "cell", ".", "__send__", "(", "method", ")", ":", "cell", "}", ".", "compact", "end" ]
Return column _n_.
[ "Return", "column", "_n_", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L65-L78
14,690
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.headings=
def headings= arrays arrays = [arrays] unless arrays.first.is_a?(Array) @headings = arrays.map do |array| row = Row.new(self, array) require_column_widths_recalc row end end
ruby
def headings= arrays arrays = [arrays] unless arrays.first.is_a?(Array) @headings = arrays.map do |array| row = Row.new(self, array) require_column_widths_recalc row end end
[ "def", "headings", "=", "arrays", "arrays", "=", "[", "arrays", "]", "unless", "arrays", ".", "first", ".", "is_a?", "(", "Array", ")", "@headings", "=", "arrays", ".", "map", "do", "|", "array", "|", "row", "=", "Row", ".", "new", "(", "self", ",", "array", ")", "require_column_widths_recalc", "row", "end", "end" ]
Set the headings
[ "Set", "the", "headings" ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L112-L119
14,691
tj/terminal-table
lib/terminal-table/table.rb
Terminal.Table.render
def render separator = Separator.new(self) buffer = style.border_top ? [separator] : [] unless @title.nil? buffer << Row.new(self, [title_cell_options]) buffer << separator end @headings.each do |row| unless row.cells.empty? buffer << row buffer << separator end end if style.all_separators buffer += @rows.product([separator]).flatten else buffer += @rows buffer << separator if style.border_bottom end buffer.map { |r| style.margin_left + r.render.rstrip }.join("\n") end
ruby
def render separator = Separator.new(self) buffer = style.border_top ? [separator] : [] unless @title.nil? buffer << Row.new(self, [title_cell_options]) buffer << separator end @headings.each do |row| unless row.cells.empty? buffer << row buffer << separator end end if style.all_separators buffer += @rows.product([separator]).flatten else buffer += @rows buffer << separator if style.border_bottom end buffer.map { |r| style.margin_left + r.render.rstrip }.join("\n") end
[ "def", "render", "separator", "=", "Separator", ".", "new", "(", "self", ")", "buffer", "=", "style", ".", "border_top", "?", "[", "separator", "]", ":", "[", "]", "unless", "@title", ".", "nil?", "buffer", "<<", "Row", ".", "new", "(", "self", ",", "[", "title_cell_options", "]", ")", "buffer", "<<", "separator", "end", "@headings", ".", "each", "do", "|", "row", "|", "unless", "row", ".", "cells", ".", "empty?", "buffer", "<<", "row", "buffer", "<<", "separator", "end", "end", "if", "style", ".", "all_separators", "buffer", "+=", "@rows", ".", "product", "(", "[", "separator", "]", ")", ".", "flatten", "else", "buffer", "+=", "@rows", "buffer", "<<", "separator", "if", "style", ".", "border_bottom", "end", "buffer", ".", "map", "{", "|", "r", "|", "style", ".", "margin_left", "+", "r", ".", "render", ".", "rstrip", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Render the table.
[ "Render", "the", "table", "." ]
e00dde32a36bbd134f1b564369c9a3085bc69852
https://github.com/tj/terminal-table/blob/e00dde32a36bbd134f1b564369c9a3085bc69852/lib/terminal-table/table.rb#L124-L144
14,692
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.analyze
def analyze Core::Runner.base_path = @path Core::Runner.config_path = @options['config'] @runner = Core::Runner.new analyze_source_codes analyze_vcs end
ruby
def analyze Core::Runner.base_path = @path Core::Runner.config_path = @options['config'] @runner = Core::Runner.new analyze_source_codes analyze_vcs end
[ "def", "analyze", "Core", "::", "Runner", ".", "base_path", "=", "@path", "Core", "::", "Runner", ".", "config_path", "=", "@options", "[", "'config'", "]", "@runner", "=", "Core", "::", "Runner", ".", "new", "analyze_source_codes", "analyze_vcs", "end" ]
Analyze rails codes. there are two steps to check rails codes, 1. prepare process, check all model and mailer files. 2. review process, check all files. if there are violations to rails best practices, output them. @param [String] path the directory of rails project @param [Hash] options
[ "Analyze", "rails", "codes", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L52-L59
14,693
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.process
def process(process) parse_files.each do |file| begin puts file if @options['debug'] @runner.send(process, file, File.read(file)) rescue StandardError if @options['debug'] warning = "#{file} looks like it's not a valid Ruby file. Skipping..." plain_output(warning, 'red') end end @bar.increment if display_bar? end @runner.send("after_#{process}") end
ruby
def process(process) parse_files.each do |file| begin puts file if @options['debug'] @runner.send(process, file, File.read(file)) rescue StandardError if @options['debug'] warning = "#{file} looks like it's not a valid Ruby file. Skipping..." plain_output(warning, 'red') end end @bar.increment if display_bar? end @runner.send("after_#{process}") end
[ "def", "process", "(", "process", ")", "parse_files", ".", "each", "do", "|", "file", "|", "begin", "puts", "file", "if", "@options", "[", "'debug'", "]", "@runner", ".", "send", "(", "process", ",", "file", ",", "File", ".", "read", "(", "file", ")", ")", "rescue", "StandardError", "if", "@options", "[", "'debug'", "]", "warning", "=", "\"#{file} looks like it's not a valid Ruby file. Skipping...\"", "plain_output", "(", "warning", ",", "'red'", ")", "end", "end", "@bar", ".", "increment", "if", "display_bar?", "end", "@runner", ".", "send", "(", "\"after_#{process}\"", ")", "end" ]
process lexical, prepare or reivew. get all files for the process, analyze each file, and increment progress bar unless debug. @param [String] process the process name, lexical, prepare or review.
[ "process", "lexical", "prepare", "or", "reivew", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L87-L101
14,694
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.parse_files
def parse_files @parse_files ||= begin files = expand_dirs_to_files(@path) files = file_sort(files) if @options['only'].present? files = file_accept(files, @options['only']) end # By default, tmp, vender, spec, test, features are ignored. %w[vendor spec test features tmp].each do |dir| files = file_ignore(files, File.join(@path, dir)) unless @options[dir] end # Exclude files based on exclude regexes if the option is set. @options['exclude'].each do |pattern| files = file_ignore(files, pattern) end %w[Capfile Gemfile Gemfile.lock].each do |file| files.unshift File.join(@path, file) end files.compact end end
ruby
def parse_files @parse_files ||= begin files = expand_dirs_to_files(@path) files = file_sort(files) if @options['only'].present? files = file_accept(files, @options['only']) end # By default, tmp, vender, spec, test, features are ignored. %w[vendor spec test features tmp].each do |dir| files = file_ignore(files, File.join(@path, dir)) unless @options[dir] end # Exclude files based on exclude regexes if the option is set. @options['exclude'].each do |pattern| files = file_ignore(files, pattern) end %w[Capfile Gemfile Gemfile.lock].each do |file| files.unshift File.join(@path, file) end files.compact end end
[ "def", "parse_files", "@parse_files", "||=", "begin", "files", "=", "expand_dirs_to_files", "(", "@path", ")", "files", "=", "file_sort", "(", "files", ")", "if", "@options", "[", "'only'", "]", ".", "present?", "files", "=", "file_accept", "(", "files", ",", "@options", "[", "'only'", "]", ")", "end", "# By default, tmp, vender, spec, test, features are ignored.", "%w[", "vendor", "spec", "test", "features", "tmp", "]", ".", "each", "do", "|", "dir", "|", "files", "=", "file_ignore", "(", "files", ",", "File", ".", "join", "(", "@path", ",", "dir", ")", ")", "unless", "@options", "[", "dir", "]", "end", "# Exclude files based on exclude regexes if the option is set.", "@options", "[", "'exclude'", "]", ".", "each", "do", "|", "pattern", "|", "files", "=", "file_ignore", "(", "files", ",", "pattern", ")", "end", "%w[", "Capfile", "Gemfile", "Gemfile.lock", "]", ".", "each", "do", "|", "file", "|", "files", ".", "unshift", "File", ".", "join", "(", "@path", ",", "file", ")", "end", "files", ".", "compact", "end", "end" ]
get all files for parsing. @return [Array] all files for parsing
[ "get", "all", "files", "for", "parsing", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L106-L131
14,695
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.expand_dirs_to_files
def expand_dirs_to_files(*dirs) extensions = %w[rb erb rake rhtml haml slim builder rxml rabl] dirs.flatten.map do |entry| next unless File.exist? entry if File.directory? entry Dir[File.join(entry, '**', "*.{#{extensions.join(',')}}")] else entry end end.flatten end
ruby
def expand_dirs_to_files(*dirs) extensions = %w[rb erb rake rhtml haml slim builder rxml rabl] dirs.flatten.map do |entry| next unless File.exist? entry if File.directory? entry Dir[File.join(entry, '**', "*.{#{extensions.join(',')}}")] else entry end end.flatten end
[ "def", "expand_dirs_to_files", "(", "*", "dirs", ")", "extensions", "=", "%w[", "rb", "erb", "rake", "rhtml", "haml", "slim", "builder", "rxml", "rabl", "]", "dirs", ".", "flatten", ".", "map", "do", "|", "entry", "|", "next", "unless", "File", ".", "exist?", "entry", "if", "File", ".", "directory?", "entry", "Dir", "[", "File", ".", "join", "(", "entry", ",", "'**'", ",", "\"*.{#{extensions.join(',')}}\"", ")", "]", "else", "entry", "end", "end", ".", "flatten", "end" ]
expand all files with extenstion rb, erb, haml, slim, builder and rxml under the dirs @param [Array] dirs what directories to expand @return [Array] all files expanded
[ "expand", "all", "files", "with", "extenstion", "rb", "erb", "haml", "slim", "builder", "and", "rxml", "under", "the", "dirs" ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L137-L149
14,696
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.file_sort
def file_sort(files) models = files.find_all { |file| file =~ Core::Check::MODEL_FILES } mailers = files.find_all { |file| file =~ Core::Check::MAILER_FILES } helpers = files.find_all { |file| file =~ Core::Check::HELPER_FILES } others = files.find_all { |file| file !~ Core::Check::MAILER_FILES && file !~ Core::Check::MODEL_FILES && file !~ Core::Check::HELPER_FILES } models + mailers + helpers + others end
ruby
def file_sort(files) models = files.find_all { |file| file =~ Core::Check::MODEL_FILES } mailers = files.find_all { |file| file =~ Core::Check::MAILER_FILES } helpers = files.find_all { |file| file =~ Core::Check::HELPER_FILES } others = files.find_all { |file| file !~ Core::Check::MAILER_FILES && file !~ Core::Check::MODEL_FILES && file !~ Core::Check::HELPER_FILES } models + mailers + helpers + others end
[ "def", "file_sort", "(", "files", ")", "models", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "=~", "Core", "::", "Check", "::", "MODEL_FILES", "}", "mailers", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "=~", "Core", "::", "Check", "::", "MAILER_FILES", "}", "helpers", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "=~", "Core", "::", "Check", "::", "HELPER_FILES", "}", "others", "=", "files", ".", "find_all", "{", "|", "file", "|", "file", "!~", "Core", "::", "Check", "::", "MAILER_FILES", "&&", "file", "!~", "Core", "::", "Check", "::", "MODEL_FILES", "&&", "file", "!~", "Core", "::", "Check", "::", "HELPER_FILES", "}", "models", "+", "mailers", "+", "helpers", "+", "others", "end" ]
sort files, models first, mailers, helpers, and then sort other files by characters. models and mailers first as for prepare process. @param [Array] files @return [Array] sorted files
[ "sort", "files", "models", "first", "mailers", "helpers", "and", "then", "sort", "other", "files", "by", "characters", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L157-L163
14,697
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.file_accept
def file_accept(files, patterns) files.select { |file| patterns.any? { |pattern| file =~ pattern } } end
ruby
def file_accept(files, patterns) files.select { |file| patterns.any? { |pattern| file =~ pattern } } end
[ "def", "file_accept", "(", "files", ",", "patterns", ")", "files", ".", "select", "{", "|", "file", "|", "patterns", ".", "any?", "{", "|", "pattern", "|", "file", "=~", "pattern", "}", "}", "end" ]
accept specific files. @param [Array] files @param [Regexp] patterns, files match any pattern will be accepted
[ "accept", "specific", "files", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L178-L180
14,698
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.output_json_errors
def output_json_errors errors_as_hashes = errors.map do |err| { filename: err.filename, line_number: err.line_number, message: err.message } end File.open(@options['output-file'], 'w+') do |file| file.write JSON.dump(errors_as_hashes) end end
ruby
def output_json_errors errors_as_hashes = errors.map do |err| { filename: err.filename, line_number: err.line_number, message: err.message } end File.open(@options['output-file'], 'w+') do |file| file.write JSON.dump(errors_as_hashes) end end
[ "def", "output_json_errors", "errors_as_hashes", "=", "errors", ".", "map", "do", "|", "err", "|", "{", "filename", ":", "err", ".", "filename", ",", "line_number", ":", "err", ".", "line_number", ",", "message", ":", "err", ".", "message", "}", "end", "File", ".", "open", "(", "@options", "[", "'output-file'", "]", ",", "'w+'", ")", "do", "|", "file", "|", "file", ".", "write", "JSON", ".", "dump", "(", "errors_as_hashes", ")", "end", "end" ]
output errors with json format.
[ "output", "errors", "with", "json", "format", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L290-L302
14,699
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.plain_output
def plain_output(message, color) if @options['without-color'] puts message else puts Colorize.send(color, message) end end
ruby
def plain_output(message, color) if @options['without-color'] puts message else puts Colorize.send(color, message) end end
[ "def", "plain_output", "(", "message", ",", "color", ")", "if", "@options", "[", "'without-color'", "]", "puts", "message", "else", "puts", "Colorize", ".", "send", "(", "color", ",", "message", ")", "end", "end" ]
plain output with color. @param [String] message to output @param [String] color
[ "plain", "output", "with", "color", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L308-L314