repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/git.rb | lib/onotole/git.rb | # frozen_string_literal: true
module Onotole
module Git
def install_user_gems_from_github
File.readlines('Gemfile').each do |l|
possible_gem_name = l.match(%r{(?:github:\s+)(?:'|")\w+/(.*)(?:'|")}i)
install_from_github possible_gem_name[1] if possible_gem_name
end
end
def create_github_repo(repo_name)
system "hub create #{repo_name}"
end
def init_git
run 'git init'
end
def git_init_commit
return unless user_choose?(:gitcommit)
say 'Init commit'
run 'git add .'
run 'git commit -m "Init commit"'
end
def gitignore_files
remove_file '.gitignore'
copy_file 'gitignore_file', '.gitignore'
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/generators/app_generator.rb | lib/onotole/generators/app_generator.rb | # frozen_string_literal: true
require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
module Onotole
class AppGenerator < Rails::Generators::AppGenerator
def self.start
class_option :database, type: :string, aliases: '-d', default: 'postgresql',
desc: "Configure for selected database (options: #{DATABASES.join('/')})"
class_option :heroku, type: :boolean, aliases: '-H', default: false,
desc: 'Create staging and production Heroku apps'
class_option :heroku_flags, type: :string, default: '',
desc: 'Set extra Heroku flags'
class_option :github, type: :string, aliases: '-G', default: nil,
desc: 'Create Github repository and add remote origin pointed to repo'
class_option :skip_test_unit, type: :boolean, aliases: '-T', default: true,
desc: 'Skip Test::Unit files'
class_option :skip_turbolinks, type: :boolean, default: true,
desc: 'Skip turbolinks gem'
class_option :skip_bundle, type: :boolean, aliases: '-B', default: true,
desc: "Don't run bundle install"
class_option :user_gems, type: :boolean, aliases: '-c', default: false,
desc: 'Ask user for gem choice'
class_option :clean_comments, type: :boolean, aliases: '--clean_comments', default: false,
desc: 'Clean up comments in config & routes files'
GEMPROCLIST.each do |gem_name|
class_option gem_name.to_sym, type: :boolean, aliases: "--#{gem_name}",
default: false, desc: "#{gem_name.to_s.humanize} gem install"
end
super
end
def finish_template
invoke :onotole_customization
super
end
def onotole_customization
invoke :prevent_double_usage
invoke :customize_gemfile
invoke :custom_gems_setup
# invoke :bundler_stubs_install
invoke :setup_git
invoke :bundleinstall
invoke :setup_development_environment
invoke :setup_test_environment
invoke :setup_production_environment
invoke :setup_staging_environment
invoke :setup_secret_token
invoke :configure_app
# invoke :create_onotole_views
# invoke :setup_stylesheets
# invoke :install_bitters
# invoke :install_refills
invoke :copy_miscellaneous_files
invoke :customize_error_pages
invoke :remove_config_comment_lines
invoke :remove_routes_comment_lines
invoke :setup_dotfiles
invoke :post_init
invoke :setup_gitignore
invoke :setup_database
invoke :create_heroku_apps
invoke :create_github_repo
invoke :setup_segment
invoke :setup_spring
invoke :pre_commit_cleanup
invoke :git_first_commit
invoke :outro
end
def customize_gemfile
build :replace_gemfile
build :set_ruby_to_version_being_used
build :set_up_heroku_specific_gems if options[:heroku]
end
def custom_gems_setup
if options[:user_gems]
build :users_gems
else
build :user_gems_from_args_or_default_set
end
end
def bundleinstall
bundle_command 'install'
build :install_user_gems_from_github
build :configure_simple_form
end
def setup_database
say 'Setting up database'
build :use_postgres_config_template if 'postgresql' == options[:database]
build :create_database
end
def setup_development_environment
say 'Setting up the development environment'
build :raise_on_missing_assets_in_test
build :raise_on_delivery_errors
build :set_test_delivery_method
build :raise_on_unpermitted_parameters
build :seeds_organisation
build :provide_setup_script
build :provide_dev_prime_task
build :provide_kill_postgres_connections_task
build :configure_generators
build :configure_i18n_for_missing_translations
build :configure_quiet_assets
build :add_dotenv_to_startup
end
def setup_test_environment
say 'Setting up the test environment'
build :set_up_factory_girl_for_rspec
build :generate_factories_file
# build :set_up_hound
build :generate_rspec
build :configure_rspec
build :configure_background_jobs_for_rspec
build :enable_database_cleaner
build :provide_shoulda_matchers_config
build :configure_spec_support_features
build :configure_ci
build :configure_i18n_for_test_environment
build :configure_action_mailer_in_specs
build :configure_capybara_webkit
end
def setup_production_environment
say 'Setting up the production environment'
build :configure_newrelic
build :configure_smtp
build :configure_rack_timeout
build :enable_rack_canonical_host
build :enable_rack_deflater
build :setup_asset_host
end
def setup_staging_environment
say 'Setting up the staging environment'
build :setup_staging_environment
end
def setup_secret_token
say 'Moving secret token out of version control'
build :setup_secret_token
end
# def create_onotole_views
# say 'Creating onotole views'
# build :create_partials_directory
# build :create_shared_flashes
# build :create_shared_javascripts
# build :create_application_layout
# end
def configure_app
say 'Configuring app'
build :configure_support_path
build :configure_action_mailer
build :configure_active_job
build :configure_time_formats
build :fix_i18n_deprecation_warning
build :setup_default_rake_task
build :configure_puma
build :set_up_forego
build :apply_vendorjs_folder
build :add_vendor_css_path
build :add_fonts_autoload
build :add_custom_formbuilder
build :copy_application_record
end
# def setup_stylesheets
# say 'Set up stylesheets'
# build :setup_stylesheets
# end
# def install_bitters
# say 'Install Bitters'
# build :install_bitters
# end
# def install_refills
# say "Install Refills"
# build :install_refills
# end
def setup_git
return if options[:skip_git]
say 'Initializing git'
invoke :init_git
end
def setup_gitignore
return if options[:skip_git]
say 'Replace .gitignore'
invoke :setup_gitignore
end
def git_first_commit
invoke :git_init_commit unless options[:skip_git]
end
def create_heroku_apps
if options[:heroku]
say 'Creating Heroku apps'
build :create_heroku_apps, options[:heroku_flags]
build :provide_review_apps_setup_script
build :set_heroku_serve_static_files
build :set_heroku_remotes
build :set_heroku_rails_secrets
build :create_heroku_pipelines_config_file
build :create_heroku_pipeline
build :provide_deploy_script
build :configure_automatic_deployment
end
end
def create_github_repo
return if options[:skip_git]
return unless options[:github]
say 'Creating Github repo'
build :create_github_repo, options[:github]
end
def setup_segment
say 'Setting up Segment'
build :setup_segment
end
def setup_dotfiles
build :copy_dotfiles
end
def setup_gitignore
build :gitignore_files
end
def git_init_commit
build :git_init_commit
end
def setup_spring
say 'Springifying binstubs'
build :setup_spring
end
def init_git
build :init_git
end
# def bundler_stubs_install
# say 'Bundler stubs install'
# build :rvm_bundler_stubs_install
# end
def copy_miscellaneous_files
say 'Copying miscellaneous support files'
build :copy_miscellaneous_files
end
def customize_error_pages
say 'Customizing the 500/404/422 pages'
build :customize_error_pages
end
def remove_config_comment_lines
build :remove_config_comment_lines if options[:clean_comments] == true
end
def remove_routes_comment_lines
build :remove_routes_comment_lines if options[:clean_comments] == true
end
def outro
build :show_goodbye_message
end
def post_init
build :post_init
build :add_bullet_gem_configuration
end
def prevent_double_usage
build :prevent_double_usage
end
def pre_commit_cleanup
build :clean_by_rubocop
end
protected
def get_builder_class
Onotole::AppBuilder
end
def using_active_record?
!options[:skip_active_record]
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/adapters/heroku.rb | lib/onotole/adapters/heroku.rb | # frozen_string_literal: true
module Onotole
module Adapters
class Heroku
def initialize(app_builder)
@app_builder = app_builder
end
def set_heroku_remotes
remotes = <<-SHELL.strip_heredoc
#{command_to_join_heroku_app('staging')}
#{command_to_join_heroku_app('production')}
git config heroku.remote staging
SHELL
app_builder.append_file 'bin/setup', remotes
end
def set_up_heroku_specific_gems
app_builder.inject_into_file(
'Gemfile',
%(\n\s\sgem "rails_stdout_logging"),
after: /group :staging, :production do/
)
end
def create_staging_heroku_app(flags)
rack_env = 'RACK_ENV=staging'
app_name = heroku_app_name_for('staging')
run_toolbelt_command "create #{app_name} #{flags}", 'staging'
run_toolbelt_command "config:add #{rack_env}", 'staging'
end
def create_production_heroku_app(flags)
app_name = heroku_app_name_for('production')
run_toolbelt_command "create #{app_name} #{flags}", 'production'
end
def set_heroku_rails_secrets
%w(staging production).each do |environment|
run_toolbelt_command(
"config:add #{app_builder.app_name.dasherize.upcase}_SECRET_KEY_BASE=#{generate_secret}",
environment
)
end
end
def provide_review_apps_setup_script
app_builder.template(
'bin_setup_review_app.erb',
'bin/setup_review_app',
force: true
)
app_builder.run 'chmod a+x bin/setup_review_app'
end
def create_heroku_pipelines_config_file
app_builder.template 'app.json.erb', 'app.json'
end
def create_heroku_pipeline
pipelines_plugin = `heroku plugins | grep pipelines`
if pipelines_plugin.empty?
puts 'You need heroku pipelines plugin. Run: heroku plugins:install heroku-pipelines'
exit 1
end
heroku_app_name = app_builder.app_name.dasherize
run_toolbelt_command(
"pipelines:create #{heroku_app_name} \
-a #{heroku_app_name}-staging --stage staging",
'staging'
)
run_toolbelt_command(
"pipelines:add #{heroku_app_name} \
-a #{heroku_app_name}-production --stage production",
'production'
)
end
def set_heroku_serve_static_files
%w(staging production).each do |environment|
run_toolbelt_command(
"config:add #{app_name.upcase}_RAILS_SERVE_STATIC_FILES=true",
environment
)
end
end
private
attr_reader :app_builder
def command_to_join_heroku_app(environment)
heroku_app_name = heroku_app_name_for(environment)
<<-SHELL
if heroku join --app #{heroku_app_name} &> /dev/null; then
git remote add #{environment} git@heroku.com:#{heroku_app_name}.git || true
printf 'You are a collaborator on the "#{heroku_app_name}" Heroku app\n'
else
printf 'Ask for access to the "#{heroku_app_name}" Heroku app\n'
fi
SHELL
end
def heroku_app_name_for(environment)
"#{app_builder.app_name.dasherize}-#{environment}"
end
def generate_secret
SecureRandom.hex(64)
end
def run_toolbelt_command(command, environment)
app_builder.run(
"heroku #{command} --remote #{environment}"
)
end
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/add_user_gems/goodbye_message.rb | lib/onotole/add_user_gems/goodbye_message.rb | # frozen_string_literal: true
module Onotole
module Goodbye
def show_goodbye_message
github_check
airbrake_check
graphviz_check
image_optim_check
rack_cors_check
ckeditor_check
devise_user_check
say_color BOLDGREEN, "Congratulations! Onotole gives you: 'Intellect+= 1'"
end
def github_check
return unless user_choose? :create_github_repo
say_color BOLDGREEN, "You can 'git push -u origin master' to your new repo
#{app_name} or check log for errors"
end
def graphviz_check
return unless user_choose?(:railroady)
return if system('dot -? > /dev/null && neato -? > /dev/null')
say_color YELLOW, 'Install graphviz for Railroady gem'
end
def airbrake_check
return unless user_choose? :airbrake
say_color YELLOW, "Remember to run 'rails generate airbrake' with your API key."
end
def image_optim_check
return unless user_choose? :image_optim
say_color YELLOW, "You may install 'svgo' for 'image_optim' by `npm install -g svgo`"
say_color YELLOW, "You may install 'pngout' for 'image_optim' from http://www.jonof.id.au/kenutils"
say_color YELLOW, 'By default this tools are switch off in image_optim.rb'
end
def rack_cors_check
return unless user_choose? :rack_cors
say_color YELLOW, 'Check your config/application.rb file for rack-cors settings for security.'
end
def ckeditor_check
return unless user_choose? :ckeditor
return if user_choose?(:carrierwave) && AppBuilder.file_storage_name
say_color YELLOW, 'Visit ckeditor homepage and install back-end for it.'
end
def devise_user_check
return unless AppBuilder.devise_model
say_color GREEN, 'Turn on devise auth in application.rb or in your controlled. It is turned off by default'
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/add_user_gems/user_gems_menu_questions.rb | lib/onotole/add_user_gems/user_gems_menu_questions.rb | # frozen_string_literal: true
module Onotole
module UserGemsMenu
def users_gems
choose_cms_engine
choose_template_engine
choose_frontend
choose_authenticate_engine
choose_authorization_engine
choose_pagimation
choose_wysiwyg
choose_develoder_tools
choose_cache_storage
choose_file_storage
# Placeholder for other gem additions
# menu description in add_gems_in_menu.rb
choose_undroup_gems
ask_cleanup_commens
users_init_commit_choice
add_github_repo_creation_choice
setup_default_gems
add_user_gems
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/add_user_gems/edit_menu_questions.rb | lib/onotole/add_user_gems/edit_menu_questions.rb | # frozen_string_literal: true
module Onotole
module EditMenuQuestions
def choose_frontend
# do not forget add in def configure_simple_form new frameworks
variants = { none: 'No front-end framework',
bootstrap3_sass: 'Twitter bootstrap v.3 sass',
bootstrap3: 'Twitter bootstrap v.3 asset pipeline',
materialize_sass: 'Materialize Sass version for Rails Asset Pipeline (http://materializecss.com)' }
gem = choice 'Select front-end framework: ', variants
add_to_user_choise(gem) if gem
end
def choose_template_engine
variants = { none: 'Erb', slim: 'Slim', haml: 'Haml' }
gem = choice 'Select markup language: ', variants
add_to_user_choise(gem) if gem
end
def choose_authenticate_engine
variants = { none: 'None', devise: 'devise 4', devise_with_model: 'devise 4 vs pre-installed model' }
gem = choice 'Select authenticate engine: ', variants
if gem == :devise_with_model
AppBuilder.devise_model = ask_stylish 'Enter devise model name:'
gem = :devise
end
add_to_user_choise(gem) if gem
end
def choose_authorization_engine
variants = { none: 'None', pundit: 'Pundit' }
gem = choice 'Select authorization engine: ', variants
add_to_user_choise(gem) if gem
end
def choose_cms_engine
variants = { none: 'None',
activeadmin: 'Activeadmin CMS (if devise selected Admin model will create automatic)',
rails_admin: 'Rails admin CMS',
rails_db: 'Rails DB. Simple pretty view in browser & xls export for models',
typus: 'Typus control panel to allow trusted users edit structured content.' }
gem = choice 'Select control panel or CMS: ', variants
add_to_user_choise(gem) if gem
show_active_admin_plugins_submenu
end
def show_active_admin_plugins_submenu
return unless user_choose? :activeadmin
variants = { none: 'None',
active_admin_import: 'The most efficient way to import for ActiveAdmin',
active_admin_theme: 'Theme, flat skin',
active_skin: 'Theme, flat, nice, good maintenance',
flattened_active_admin: 'Theme, bring your Active Admin up-to-date with this customizable add on',
active_admin_bootstrap: 'Theme, simple bootstrap (sass) elements',
face_of_active_admin: 'Theme for ActiveAdmin with glyphicons and flattens',
active_admin_simple_life: 'Automatize routine with creation simple menus in ActiveAdmin with minimum code duplication.' }
themes = [:active_admin_theme, :active_skin, :flattened_active_admin]
multiple_choice('Select activeadmin plug-ins (Themes are SASS or SCSS only).', variants).each do |gem|
add_to_user_choise gem
if themes.include? gem
AppBuilder.use_asset_pipelline = false
AppBuilder.active_admin_theme_selected = true
end
end
end
def choose_pagimation
if user_choose? :activeadmin
add_to_user_choise(:kaminari)
return
end
variants = { none: 'None',
will_paginate: 'Will paginate',
kaminari: 'Kaminari' }
gem = choice 'Select paginator: ', variants
add_to_user_choise(gem) if gem
end
def choose_develoder_tools
variants = { none: 'None',
faker: 'Gem for generate fake data in testing',
rubocop: 'Code inspector and code formatting tool',
rubycritic: 'A Ruby code quality reporter',
guard: 'Guard (with RSpec, livereload, rails, migrate, bundler)',
guard_rubocop: 'Auto-declare code miss in guard',
bundler_audit: 'Extra possibilities for gems version control',
airbrake: 'Airbrake error logging',
annotate: 'Annotate Rails classes with schema and routes info',
overcommit: 'A fully configurable and extendable Git hook manager',
railroady: 'Model and controller UML class diagram generator',
hirbunicode: 'Hirb unicode support',
dotenv_heroku: 'dotenv-heroku support',
image_optim: 'Optimize images (jpeg, png, gif, svg) using external utilities',
mailcatcher: 'Catches mail and serves it through a dream. http://mailcatcher.me',
rack_mini_profiler: 'Middleware that displays speed badge for every html page.',
flamegraph: 'Rack_mini_profiler awesome graphics generator. Need stackprof gem',
stackprof: 'A sampling call-stack profiler for ruby 2.1+',
git_up: 'git-up(1) -- fetch and rebase all locally-tracked remote branches',
meta_request: 'Rails meta panel in chrome console.'\
" Very usefull in\n#{' ' * 24}AJAX debugging. Link for chrome"\
" add-on in Gemfile.\n#{' ' * 24}Do not delete comments if you need this link",
active_record_doctor: 'Active Record Doctor helps to index unindexed foreign keys' }
multiple_choice('Write numbers of all preferred gems.', variants).each do |gem|
add_to_user_choise gem
end
end
def choose_wysiwyg
variants = { none: 'None',
ckeditor: 'CKEditor text editor designed for web content creation.',
tinymce: 'TinyMCE with the Rails asset pipeline' }
gem = choice 'Select wysiwyg: ', variants
add_to_user_choise(gem) if gem
end
def choose_undroup_gems
variants = { none: 'None',
responders: 'A set of responders modules to dry up your Rails 4.2+ app.',
activerecord_import: 'A library for bulk inserting data using ActiveRecord',
paper_trail: 'Track changes to your models data. For auditing or versioning',
cyrillizer: 'Character conversion from latin to cyrillic and vice versa',
validates_timeliness: 'Date and time validation plugin for ActiveModel and Rails',
font_awesome_sass: 'Font-Awesome Sass gem for use in Ruby/Rails projects',
fotoramajs: 'Fotorama JS gallery for Rails http://fotorama.io/',
prawn: 'Prawn gem for PDF support vs prawn-table for easy tables',
axlsx_rails: 'XLS support, cyrillic support, good support at all',
geocoder: 'Complete Ruby geocoding solution. http://www.rubygeocoder.com',
gmaps4rails: 'Enables easy Google map + overlays creation. http://apneadiving.github.io/',
rack_cors: 'Rack Middleware for handling Cross-Origin Resource Sharing (CORS).',
newrelic_rpm: 'New Relic RPM Ruby Agent http://www.newrelic.com',
invisible_captcha: 'Unobtrusive and flexible spam protection for RoR apps',
sitemap_generator: 'SitemapGenerator is the easiest way to generate Sitemaps in Ruby.',
therubyracer: 'JS code execution in Ruby' }
multiple_choice('Write numbers of all preferred gems.', variants).each do |gem|
add_to_user_choise gem
end
add_to_user_choise :underscore_rails if user_choose?(:gmaps4rails)
end
def choose_cache_storage
variants = { none: 'Default',
redis: 'Redis db ruby library',
redis_rails: 'Provides a full set of stores (Cache, Session, HTTP Cache)',
redis_namespace: 'Provides an interface to a namespaced subset of your redis keyspace' }
multiple_choice('Select cache storage and plug-ins.', variants).each do |gem|
add_to_user_choise gem
end
add_to_user_choise :redis if user_choose?(:redis_rails) || user_choose?(:redis_namespace)
end
def choose_file_storage
variants = { none: 'None',
carrierwave: 'carrierwave v0.10',
carrierwave_with_uploader: 'carrierwave+mini_magick v0.10 pre-installed uploader' }
gem = choice 'Select file storage engine: ', variants
if gem == :carrierwave_with_uploader
AppBuilder.file_storage_name = ask_stylish('Enter uploader name:').downcase
gem = :carrierwave
end
add_to_user_choise(gem) if gem
end
# template for yes/no question
#
# def supeawesome_gem
# gem_name = __callee__.to_s.gsub(/_gem$/, '')
# gem_description = 'Awesome gem description'
# add_to_user_choise( yes_no_question( gem_name,
# gem_description)) unless options[gem_name]
# end
# TODO: move all this to other module
def users_init_commit_choice
variants = { none: 'No', gitcommit: 'Yes' }
sel = choice 'Make init commit in the end? ', variants
add_to_user_choise(sel) unless sel == :none
end
def ask_cleanup_commens
return if options[:clean_comments]
variants = { none: 'No', clean_comments: 'Yes' }
sel = choice 'Delete comments in Gemfile, routes.rb & config files? ',
variants
add_to_user_choise(sel) unless sel == :none
end
def add_github_repo_creation_choice
variants = { none: 'No', create_github_repo: 'Yes' }
sel = choice "Create github repo #{app_name}?", variants
add_to_user_choise(sel) unless sel == :none
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/add_user_gems/before_bundle_patch.rb | lib/onotole/add_user_gems/before_bundle_patch.rb | # frozen_string_literal: true
module Onotole
module BeforeBundlePatch
def add_user_gems
add_to_user_choise(:devise_bootstrap_views) if user_choose?(:bootstrap3_sass) && user_choose?(:devise)
GEMPROCLIST.each do |g|
send "add_#{g}_gem" if user_choose? g.to_sym
end
end
def setup_default_gems
add_to_user_choise(:normalize)
end
def add_haml_gem
inject_into_file('Gemfile', "\ngem 'haml-rails'", after: '# user_choice')
end
def add_dotenv_heroku_gem
inject_into_file('Gemfile', "\n gem 'dotenv-heroku'",
after: 'group :development do')
append_file 'Rakefile', %(\nrequire 'dotenv-heroku/tasks' if ENV['RACK_ENV'] == 'test' || ENV['RACK_ENV'] == 'development'\n)
end
def add_slim_gem
inject_into_file('Gemfile', "\ngem 'slim-rails'", after: '# user_choice')
inject_into_file('Gemfile', "\n gem 'html2slim'", after: 'group :development do')
end
def add_rails_db_gem
inject_into_file('Gemfile', "\n gem 'rails_db'\n gem 'axlsx_rails'", after: '# user_choice')
end
def add_rubocop_gem
inject_into_file('Gemfile', "\n gem 'rubocop', require: false",
after: 'group :development do')
copy_file 'rubocop.yml', '.rubocop.yml'
end
def add_guard_gem
t = <<-TEXT.chomp
gem 'guard'
gem 'guard-livereload', '~> 2.4', require: false
gem 'guard-puma', require: false
gem 'guard-migrate', require: false
gem 'guard-rspec', require: false
gem 'guard-bundler', require: false
TEXT
inject_into_file('Gemfile', t, after: 'group :development do')
end
def add_guard_rubocop_gem
if user_choose?(:guard) && user_choose?(:rubocop)
inject_into_file('Gemfile', "\n gem 'guard-rubocop'",
after: 'group :development do')
else
say_color RED, 'You need Guard & Rubocop gems for this add-on'
end
end
def add_meta_request_gem
inject_into_file('Gemfile',
"\n gem 'meta_request' # link for chrome add-on. "\
'https://chrome.google.com/webstore/detail/'\
'railspanel/gjpfobpafnhjhbajcjgccbbdofdckggg',
after: 'group :development do')
end
def add_faker_gem
inject_into_file('Gemfile', "\n gem 'faker'", after: 'group :development, :test do')
end
def add_bundler_audit_gem
copy_file 'bundler_audit.rake', 'lib/tasks/bundler_audit.rake'
append_file 'Rakefile', %(\ntask default: "bundler:audit"\n)
end
def add_bootstrap3_sass_gem
inject_into_file('Gemfile', "\ngem 'bootstrap-sass', '~> 3.3.6'",
after: '# user_choice')
end
def add_airbrake_gem
inject_into_file('Gemfile', "\ngem 'airbrake'",
after: '# user_choice')
end
def add_bootstrap3_gem
inject_into_file('Gemfile', "\ngem 'twitter-bootstrap-rails'",
after: '# user_choice')
inject_into_file('Gemfile', "\ngem 'devise-bootstrap-views'",
after: '# user_choice') if user_choose?(:devise)
end
def add_devise_gem
devise_conf = <<-TEXT
# v.3.5 syntax. will be deprecated in 4.0
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_in) do |user_params|
user_params.permit(:email, :password, :remember_me)
end
devise_parameter_sanitizer.permit(:sign_up) do |user_params|
user_params.permit(:email, :password, :password_confirmation)
end
end
protected :configure_permitted_parameters
TEXT
inject_into_file('Gemfile', "\ngem 'devise'", after: '# user_choice')
inject_into_file('app/controllers/application_controller.rb',
"\nbefore_action :configure_permitted_parameters, if: :devise_controller?",
after: 'class ApplicationController < ActionController::Base')
inject_into_file('app/controllers/application_controller.rb', devise_conf,
after: 'protect_from_forgery with: :exception')
copy_file 'devise_rspec.rb', 'spec/support/devise.rb'
copy_file 'devise.ru.yml', 'config/locales/devise.ru.yml'
end
def add_responders_gem
inject_into_file('Gemfile', "\ngem 'responders'", after: '# user_choice')
end
def add_hirbunicode_gem
inject_into_file('Gemfile', "\ngem 'hirb-unicode'", after: '# user_choice')
end
def add_tinymce_gem
inject_into_file('Gemfile', "\ngem 'tinymce-rails'", after: '# user_choice')
inject_into_file('Gemfile', "\ngem 'tinymce-rails-langs'", after: '# user_choice')
copy_file 'tinymce.yml', 'config/tinymce.yml'
end
def add_annotate_gem
inject_into_file('Gemfile', "\n gem 'annotate'", after: 'group :development do')
end
def add_overcommit_gem
inject_into_file('Gemfile', "\n gem 'overcommit'", after: 'group :development do')
copy_file 'onotole_overcommit.yml', '.overcommit.yml'
rubocop_overcommit = <<-OVER
RuboCop:
enabled: true
description: 'Analyzing with RuboCop'
required_executable: 'rubocop'
flags: ['--format=emacs', '--force-exclusion', '--display-cop-names']
install_command: 'gem install rubocop'
include:
- '**/*.gemspec'
- '**/*.rake'
- '**/*.rb'
- '**/Gemfile'
- '**/Rakefile'
OVER
append_file '.overcommit.yml', rubocop_overcommit if user_choose?(:rubocop)
end
def add_activerecord_import_gem
inject_into_file('Gemfile', "\ngem 'activerecord-import'", after: '# user_choice')
end
def add_activeadmin_gem
inject_into_file('Gemfile', "\ngem 'activeadmin', github: 'activeadmin'", after: '# user_choice')
inject_into_file('Gemfile', "\ngem 'kaminari-i18n'", after: '# user_choice')
copy_file 'activeadmin.en.yml', 'config/locales/activeadmin.en.yml'
copy_file 'activeadmin.ru.yml', 'config/locales/activeadmin.ru.yml'
# it still live https://github.com/Prelang/feedback/issues/14 and this patch helps
run 'mkdir app/inputs'
copy_file 'inet_input.rb', 'app/inputs/inet_input.rb'
end
# def add_administrate_gem
# inject_into_file('Gemfile', "\ngem 'administrate'", after: '# user_choice')
# end
def add_rails_admin_gem
inject_into_file('Gemfile', "\ngem 'rails_admin'", after: '# user_choice')
end
def add_rubycritic_gem
inject_into_file('Gemfile', "\n gem 'rubycritic', :require => false",
after: 'group :development do')
end
def add_railroady_gem
inject_into_file('Gemfile', "\n gem 'railroady'", after: 'group :development do')
end
def add_typus_gem
inject_into_file('Gemfile', "\n gem 'typus', github: 'typus/typus'", after: '# user_choice')
end
def add_will_paginate_gem
inject_into_file('Gemfile', "\ngem 'will_paginate', '~> 3.0.6'",
after: '# user_choice')
inject_into_file('Gemfile', "\ngem 'will_paginate-bootstrap'",
after: '# user_choice') if user_choose?(:bootstrap3) ||
user_choose?(:bootstrap3_sass)
end
def add_kaminari_gem
inject_into_file('Gemfile', "\ngem 'kaminari'", after: '# user_choice')
inject_into_file('Gemfile', "\ngem 'kaminari-i18n'", after: '# user_choice')
copy_file 'kaminari.rb', 'config/initializers/kaminari.rb'
inject_into_file('Gemfile', "\ngem 'bootstrap-kaminari-views'",
after: '# user_choice') if user_choose?(:bootstrap3) ||
user_choose?(:bootstrap3_sass)
end
def add_active_admin_import_gem
inject_into_file('Gemfile', "\ngem 'active_admin_import'", after: '# user_choice')
end
def add_active_admin_theme_gem
inject_into_file('Gemfile', "\ngem 'active_admin_theme'", after: '# user_choice')
end
def add_paper_trail_gem
inject_into_file('Gemfile', "\ngem 'paper_trail'", after: '# user_choice')
end
def add_validates_timeliness_gem
inject_into_file('Gemfile', "\ngem 'validates_timeliness'", after: '# user_choice')
end
def add_active_skin_gem
inject_into_file('Gemfile', "\ngem 'active_skin'", after: '# user_choice')
end
def add_flattened_active_admin_gem
inject_into_file('Gemfile', "\ngem 'flattened_active_admin'", after: '# user_choice')
end
def add_font_awesome_sass_gem
inject_into_file('Gemfile', "\ngem 'font-awesome-sass', '~> 4.5.0'", after: '# user_choice')
end
def add_cyrillizer_gem
inject_into_file('Gemfile', "\ngem 'cyrillizer'", after: '# user_choice')
end
def add_ckeditor_gem
inject_into_file('Gemfile', "\ngem 'ckeditor'", after: '# user_choice')
end
def add_devise_bootstrap_views_gem
inject_into_file('Gemfile', "\ngem 'devise-bootstrap-views'", after: '# user_choice')
end
def add_axlsx_rails_gem
inject_into_file('Gemfile', "\ngem 'axlsx_rails'", after: '# user_choice')
end
def add_axlsx_gem
inject_into_file('Gemfile', "\ngem 'axlsx'", after: '# user_choice')
end
def add_face_of_active_admin_gem
inject_into_file('Gemfile', "\ngem 'face_of_active_admin'", after: '# user_choice')
end
def add_prawn_gem
inject_into_file('Gemfile', "\ngem 'prawn'", after: '# user_choice')
inject_into_file('Gemfile', "\ngem 'prawn-table'", after: '# user_choice')
end
def add_fotoramajs_gem
inject_into_file('Gemfile', "\ngem 'fotoramajs'", after: '# user_choice')
end
def add_geocoder_gem
inject_into_file('Gemfile', "\ngem 'geocoder'", after: '# user_choice')
end
def add_gmaps4rails_gem
inject_into_file('Gemfile', "\ngem 'gmaps4rails'", after: '# user_choice')
end
def add_underscore_rails_gem
inject_into_file('Gemfile', "\ngem 'underscore-rails'", after: '# user_choice')
end
def add_image_optim_gem
inject_into_file('Gemfile', "\n gem 'image_optim_pack'", after: 'group :development do')
inject_into_file('Gemfile', "\n gem 'image_optim'", after: 'group :development do')
end
def add_mailcatcher_gem
inject_into_file('Gemfile', "\n gem 'mailcatcher'", after: 'group :development do')
end
def add_rack_cors_gem
inject_into_file('Gemfile', "\ngem 'rack-cors', :require => 'rack/cors'", after: '# user_choice')
end
def add_rack_mini_profiler_gem
inject_into_file('Gemfile', "\n gem 'rack-mini-profiler', require: false", after: '# user_choice')
copy_file 'rack_mini_profiler.rb', 'config/initializers/rack_mini_profiler.rb'
end
def add_newrelic_rpm_gem
inject_into_file('Gemfile', "\ngem 'newrelic_rpm'", after: '# user_choice')
end
def add_active_admin_simple_life_gem
inject_into_file('Gemfile', "\ngem 'active_admin_simple_life'", after: '# user_choice')
end
def add_flamegraph_gem
inject_into_file('Gemfile', "\n gem 'flamegraph'", after: 'group :development do')
end
def add_stackprof_gem
inject_into_file('Gemfile', "\n gem 'stackprof'", after: 'group :development do')
end
def add_redis_gem
inject_into_file('Gemfile', "\ngem 'redis', '~>3.2'", after: '# user_choice')
end
def add_redis_rails_gem
inject_into_file('Gemfile', "\ngem 'redis-rails'", after: '# user_choice')
end
def add_redis_namespace_gem
inject_into_file('Gemfile', "\ngem 'redis-namespace'", after: '# user_choice')
end
def add_carrierwave_gem
inject_into_file('Gemfile', "\ngem 'carrierwave', '~> 0.10.0'", after: '# user_choice')
inject_into_file('Gemfile',
"\ngem 'mini_magick', '~> 4.5.0'",
after: '# user_choice') if AppBuilder.file_storage_name
end
def add_invisible_captcha_gem
inject_into_file('Gemfile', "\ngem 'invisible_captcha'", after: '# user_choice')
end
def add_sitemap_generator_gem
inject_into_file('Gemfile', "\n gem 'sitemap_generator', :require => false", after: 'group :development do')
end
def add_materialize_sass_gem
inject_into_file('Gemfile', "\ngem 'materialize-sass'", after: '# user_choice')
end
def add_active_record_doctor_gem
inject_into_file('Gemfile', "\n gem 'active_record_doctor'", after: 'group :development do')
end
def add_therubyracer_gem
inject_into_file('Gemfile', "\n gem 'therubyracer'", after: '# user_choice')
end
def add_pundit_gem
inject_into_file('Gemfile', "\n gem 'pundit'", after: '# user_choice')
end
def add_git_up_gem
inject_into_file('Gemfile', "\n gem 'git-up'", after: 'group :development do')
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
kvokka/onotole | https://github.com/kvokka/onotole/blob/3c14f28863dbbad1a4c5f072b706154e326eb276/lib/onotole/add_user_gems/after_install_patch.rb | lib/onotole/add_user_gems/after_install_patch.rb | # frozen_string_literal: true
module Onotole
module AfterInstallPatch
def post_init
install_queue = [:redis, :redis_rails, :redis_namespace,
:carrierwave,
:sitemap_generator,
:ckeditor,
:materialize_sass,
:fotoramajs,
:underscore_rails,
:gmaps4rails,
:mailcatcher,
:rack_cors,
:image_optim,
:devise,
:validates_timeliness,
:paper_trail,
:responders,
:typus,
:annotate,
:overcommit,
:activeadmin, :active_admin_theme, :acive_skin, :flattened_active_admin,
:face_of_active_admin, :active_admin_bootstrap,
:rails_admin,
:pundit,
:guard, :guard_rubocop,
:bootstrap3_sass, :bootstrap3, :devise_bootstrap_views,
:active_admin_theme,
:font_awesome_sass,
:normalize,
:tinymce,
:rubocop,
:create_github_repo]
install_queue.each { |g| send "after_install_#{g}" if user_choose? g }
delete_comments
end
def after_install_devise
rails_generator 'devise:install'
if AppBuilder.devise_model
rails_generator "devise #{AppBuilder.devise_model.titleize}"
inject_into_file('app/controllers/application_controller.rb',
"\n# before_action :authenticate_#{AppBuilder.devise_model.downcase}!",
after: 'before_action :configure_permitted_parameters, if: :devise_controller?')
end
if user_choose?(:bootstrap3)
rails_generator 'devise:views:bootstrap_templates'
else
rails_generator 'devise:views'
end
end
def after_install_rubocop
run 'touch .rubocop_todo.yml'
t = <<-TEXT
if ENV['RACK_ENV'] == 'test' || ENV['RACK_ENV'] == 'development'
require 'rubocop/rake_task'
RuboCop::RakeTask.new
end
TEXT
append_file 'Rakefile', t
clean_by_rubocop
end
def after_install_guard
bundle_command "exec guard init #{quiet_suffix}"
replace_in_file 'Guardfile',
"guard 'puma' do",
'guard :puma, port: 3000 do', quiet_err = true
end
def after_install_guard_rubocop
if user_choose?(:guard) && user_choose?(:rubocop)
cover_def_by 'Guardfile', 'guard :rubocop do', 'group :red_green_refactor, halt_on_fail: true do'
cover_def_by 'Guardfile', 'guard :rspec, ', 'group :red_green_refactor, halt_on_fail: true do'
replace_in_file 'Guardfile',
'guard :rubocop do',
'guard :rubocop, all_on_start: false do', quiet_err = true
replace_in_file 'Guardfile',
'guard :rspec, cmd: "bundle exec rspec" do',
"guard :rspec, cmd: 'bundle exec rspec', failed_mode: :keep do", quiet_err = true
end
end
def after_install_bootstrap3_sass
setup_stylesheets
AppBuilder.use_asset_pipelline = false
touch AppBuilder.app_file_scss
append_file(AppBuilder.app_file_scss,
"\n@import 'bootstrap-sprockets';
\n@import 'bootstrap';")
inject_into_file(AppBuilder.js_file, "\n//= require bootstrap-sprockets",
after: '//= require jquery_ujs')
copy_file 'bootstrap_flash_helper.rb', 'app/helpers/bootstrap_flash_helper.rb'
end
def after_install_bootstrap3
AppBuilder.use_asset_pipelline = true
remove_file 'app/views/layouts/application.html.erb'
rails_generator 'bootstrap:install static'
rails_generator 'bootstrap:layout'
end
def after_install_normalize
if AppBuilder.use_asset_pipelline
touch AppBuilder.app_file_css
inject_into_file(AppBuilder.app_file_css, " *= require normalize-rails\n",
after: " * file per style scope.\n *\n")
else
touch AppBuilder.app_file_scss
inject_into_file(AppBuilder.app_file_scss, "\n@import 'normalize-rails';",
after: '@charset "utf-8";')
end
end
def after_install_tinymce
inject_into_file(AppBuilder.js_file, "\n//= require tinymce-jquery",
after: '//= require jquery_ujs')
end
def after_install_responders
rails_generator 'responders:install'
end
def after_install_create_github_repo
create_github_repo(app_name)
end
def after_install_annotate
rails_generator 'annotate:install'
end
def after_install_overcommit
bundle_command 'exec overcommit --install'
bundle_command 'exec overcommit --sign'
inject_into_file('bin/setup', "\novercommit --install\novercommit --sign", after: '# User addons installation')
end
def after_install_activeadmin
if user_choose? :devise
rails_generator 'active_admin:install'
else
rails_generator 'active_admin:install --skip-users'
end
end
def after_install_rails_admin
rails_generator 'rails_admin:install'
end
def after_install_typus
rails_generator 'typus'
rails_generator 'typus:migration'
rails_generator 'typus:views'
end
def after_install_paper_trail
rails_generator 'paper_trail:install'
end
def after_install_validates_timeliness
rails_generator 'validates_timeliness:install'
end
def after_install_font_awesome_sass
if AppBuilder.use_asset_pipelline
inject_into_file(AppBuilder.app_file_css,
" *= require font-awesome-sprockets\n *= require font-awesome\n",
after: " * file per style scope.\n *\n")
else
touch AppBuilder.app_file_scss
append_file(AppBuilder.app_file_scss,
"\n@import 'font-awesome-sprockets';\n@import 'font-awesome';")
end
end
def after_install_devise_bootstrap_views
return if AppBuilder.use_asset_pipelline
touch AppBuilder.app_file_scss
append_file(AppBuilder.app_file_scss, "\n@import 'devise_bootstrap_views';")
rails_generator 'devise:views:bootstrap_templates'
end
def after_install_active_admin_bootstrap
return unless user_choose?(:bootstrap3_sass) || user_choose?(:activeadmin)
AppBuilder.use_asset_pipelline = false
copy_file 'admin_bootstrap.scss', 'vendor/assets/stylesheets/active_admin/admin_bootstrap.scss'
copy_file 'active_admin.scss', 'vendor/assets/stylesheets/active_admin.scss'
remove_file 'app/assets/stylesheets/active_admin.scss'
end
def after_install_active_admin_theme
return unless user_choose? :activeadmin
File.open('app/assets/stylesheets/active_admin.scss', 'a') do |f|
f.write "\n@import 'wigu/active_admin_theme';"
end
end
def after_install_acive_skin
return unless user_choose? :activeadmin
File.open('app/assets/stylesheets/active_admin.scss', 'a') do |f|
f.write "\n@import 'active_skin';\n\\\\$skinLogo: url('admin_logo.png') no-repeat 0 0;"
end
end
def after_install_flattened_active_admin
return unless user_choose? :activeadmin
File.open('app/assets/stylesheets/active_admin.scss', 'w') do |f|
f.write "\n@import 'flattened_active_admin/variables';
\n@import 'flattened_active_admin/mixins';
\n@import 'flattened_active_admin/base';"
end
rails_generator 'flattened_active_admin:variables'
end
def after_install_face_of_active_admin
return unless user_choose? :activeadmin
File.open('app/assets/stylesheets/active_admin.scss', 'w') do |f|
f.write "\n@import 'face_of_active_admin_variables';
\n@import 'face_of_active_admin/mixins';
\n@import 'face_of_active_admin/base';"
end
append_file 'app/assets/javascripts/active_admin.js.coffee',
"\n#= require face_of_active_admin/base"
rails_generator 'face_of_active_admin:variables'
end
def after_install_fotoramajs
if AppBuilder.use_asset_pipelline
inject_into_file(AppBuilder.app_file_css, " *= require fotorama\n",
after: " * file per style scope.\n *\n")
else
touch AppBuilder.app_file_scss
append_file(AppBuilder.app_file_scss, "\n@import 'fotorama';")
end
inject_into_file(AppBuilder.js_file, "\n//= require fotorama",
after: '//= require jquery_ujs')
end
def after_install_underscore_rails
inject_into_file(AppBuilder.js_file, "\n//= require underscore",
after: '//= require jquery_ujs')
end
def after_install_gmaps4rails
inject_into_file(AppBuilder.js_file, "\n//= require gmaps/google",
after: '//= require underscore')
end
def after_install_mailcatcher
config = <<-RUBY
if system ('lsof -i :1025 | grep mailcatch > /dev/null')
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { address: "localhost", port: 1025 }
else
config.action_mailer.delivery_method = :file
end
RUBY
replace_in_file 'config/environments/development.rb',
'config.action_mailer.delivery_method = :file', config
end
def after_install_rack_cors
config = <<-RUBY
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
RUBY
inject_into_class 'config/application.rb', 'Application', config
end
def after_install_ckeditor
inject_into_file(AppBuilder.js_file, "\n//= require ckeditor/init",
after: '//= require jquery_ujs')
append_file('config/initializers/assets.rb',
"\nRails.application.config.assets.precompile += %w( ckeditor/* )")
rails_generator 'ckeditor:install --orm=active_record '\
'--backend=carrierwave' if user_choose? :carrierwave
end
def after_install_image_optim
File.open('config/initializers/image_optim.rb', 'w') do |f|
f.write 'Rails.application.config.assets.image_optim = {svgo: false, pngout: false}'
end
end
def after_install_redis
config = %q(
config.cache_store = :redis_store, "#{ENV['REDIS_PATH']}/cache", { expires_in: 90.minutes }
)
File.open('config/initializers/redis.rb', 'w') { |f| f.write "$redis = Redis.new\n" }
%w(development production).each do |env|
inject_into_file "config/environments/#{env}.rb", config,
after: "Rails.application.configure do\n"
end
append_file '.env', 'REDIS_PATH=redis://localhost:6379/0'
append_file '.env.production', 'REDIS_PATH=redis://localhost:6379/0'
copy_file 'redis.rake', 'lib/tasks/redis.rake'
rubocop_conf = <<-DATA
Style/GlobalVars:
Enabled: false
DATA
File.open('.rubocop.yml', 'a') { |f| f.write rubocop_conf } if user_choose? :rubocop
end
def after_install_redis_namespace
return unless user_choose? :redis
append_file 'config/initializers/redis.rb',
br("$ns_redis = Redis::Namespace.new(:#{app_name}, redis: $redis)")
end
def after_install_redis_rails
return unless user_choose? :redis
append_file 'config/initializers/redis.rb', br(app_name.classify.to_s)
append_file 'config/initializers/redis.rb',
%q(::Application.config.session_store :redis_store, servers: "#{ENV['REDIS_PATH']}/session")
end
def after_install_carrierwave
copy_file 'carrierwave.rb', 'config/initializers/carrierwave.rb'
return unless AppBuilder.file_storage_name
rails_generator "uploader #{AppBuilder.file_storage_name}"
uploader_path = "app/uploaders/#{AppBuilder.file_storage_name}_uploader.rb"
config = "\n include CarrierWave::MiniMagick\n"
inject_into_class uploader_path, "#{AppBuilder.file_storage_name.classify}Uploader", config
end
def after_install_sitemap_generator
bundle_command 'exec sitemap:install'
end
def after_install_pundit
rails_generator 'pundit:install'
if user_choose? :activeadmin
initializer_path = 'config/initializers/active_admin.rb'
config = %(
config.authentication_method = :authenticate_admin_user!
config.authorization_adapter = ActiveAdmin::PunditAdapter
config.pundit_default_policy = "ApplicationPolicy"
)
inject_into_file initializer_path, config, after: 'ActiveAdmin.setup do |config|'
mkdir_and_touch 'app/policies/active_admin'
copy_file 'pundit/active_admin/comment_policy.rb', 'app/policies/active_admin/comment_policy.rb'
copy_file 'pundit/active_admin/page_policy.rb', 'app/policies/active_admin/page_policy.rb'
end
end
def after_install_materialize_sass
setup_stylesheets
AppBuilder.use_asset_pipelline = false
touch AppBuilder.app_file_scss
append_file(AppBuilder.app_file_scss, "\n@import 'materialize';")
inject_into_file(AppBuilder.js_file, "\n//= require materialize-sprockets",
after: '//= require jquery_ujs')
end
end
end
| ruby | MIT | 3c14f28863dbbad1a4c5f072b706154e326eb276 | 2026-01-04T17:54:02.890450Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/serializers/measure_serializer.rb | app/serializers/measure_serializer.rb | class MeasureSerializer < ActiveModel::Serializer
attributes :id
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/serializers/health_data_standards/cqm/measure_serializer.rb | app/serializers/health_data_standards/cqm/measure_serializer.rb | module HealthDataStandards
module CQM
class MeasureSerializer < ActiveModel::Serializer
attributes :_id, :name, :category, :hqmf_id, :type, :sub_id, :lower_is_better, :cms_id,:description
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/serializers/api/measure_serializer.rb | app/serializers/api/measure_serializer.rb | class Api::MeasureSerializer < ActiveModel::Serializer
attributes :_id, :name, :category, :hqmf_id, :type, :cms_id
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/helpers/reports_helper.rb | app/helpers/reports_helper.rb | module ReportsHelper
def generate_cat3(provider, effective_date, measure_ids)
exporter = HealthDataStandards::Export::Cat3.new
effective_date ||= Time.gm(2012,12,31)
end_date = DateTime.new(effective_date.to_i, 12, 31)
provider_filter = {}
provider_filter['filters.providers'] = provider.id.to_s
filter = measure_ids==["all"] ? {} : {:cms_id.in => measure_ids}
return exporter.export(HealthDataStandards::CQM::Measure.top_level.where(filter),
generate_header(provider),
effective_date.to_i,
end_date.years_ago(1),
end_date, provider_filter)
end
def generate_header(provider)
header = Qrda::Header.new(APP_CONFIG["cda_header"])
header.identifier.root = UUID.generate
header.authors.each {|a| a.time = Time.now}
header.legal_authenticator.time = Time.now
header.performers << provider
header
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/helpers/pagination_helper.rb | app/helpers/pagination_helper.rb | module PaginationHelper
def paginate(base_url,collection)
set_pagination_params
count = collection.count
links = generate_links(base_url,count,@per_page,@page)
response.headers["Link"] = links.join(",") if !links.empty?
collection.skip(@offset).limit(@per_page)
end
def generate_links(base_url,count,per_page,page)
links = []
total_pages = count/per_page
total_pages = total_pages +1 if (count%per_page ) != 0
next_page = page < total_pages
prev_page = page > 1 && total_pages != 1
links << generate_link(base_url,1,per_page,"first") if total_pages > 1
links << generate_link(base_url,total_pages,per_page,"last") if total_pages != 1
links << generate_link(base_url,page-1,per_page,"prev") if prev_page
links << generate_link(base_url,page+1,per_page,"next") if next_page
links
end
def generate_link(base_url, page, per_page, rel)
%{<#{base_url}?page=#{page}&per_page=#{per_page}>; rel="#{rel}" }
end
def set_pagination_params
@page = (params[:page] || 1).to_i
@per_page = (params[:per_page] || 100).to_i
@per_page = 200 if @per_page > 200
@offset = (@page-1)*@per_page
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
def render_js(options = nil, extra_options = {}, &block)
escape_javascript(render(options, extra_options, &block))
end
def numerator_width(numerator, patient_count)
if numerator && !patient_count.zero?
"#{((numerator / patient_count.to_f) * 100).to_i}%"
else
'0%'
end
end
def denominator_width(numerator, denominator, patient_count)
if numerator && denominator && !patient_count.zero?
"#{(((denominator - numerator)/ patient_count.to_f) * 100).to_i}%"
else
'0%'
end
end
def exclusion_width(exclusion, patient_count)
if exclusion && !patient_count.zero?
"#{((exclusion / patient_count.to_f) * 100).to_i}%"
else
'0%'
end
end
def display_time(seconds_since_epoch)
Time.at(seconds_since_epoch).strftime('%m/%d/%Y')
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/helpers/logs_helper.rb | app/helpers/logs_helper.rb | module LogsHelper
def time_range_params_plus(url_params_hash)
url_params_hash[:log_start_date] = params[:log_start_date] if params[:log_start_date]
url_params_hash[:log_end_date] = params[:log_end_date] if params[:log_end_date]
url_params_hash
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/helpers/home_helper.rb | app/helpers/home_helper.rb | module HomeHelper
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/home_controller.rb | app/controllers/home_controller.rb | class HomeController < ApplicationController
before_filter :authenticate_user!, :validate_authorization!
def index
# TODO base this on provider
@patient_count = Record.count
@categories = HealthDataStandards::CQM::Measure.categories([:lower_is_better, :type])
end
private
def validate_authorization!
authorize! :read, HealthDataStandards::CQM::Measure
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/logs_controller.rb | app/controllers/logs_controller.rb | class LogsController < ApplicationController
before_filter :authenticate_user!
before_filter :validate_authorization!
# All attributes of the Log class are valid to sort on except ones that start with an underscore.
VALID_SORTABLE_COLUMNS = Log.fields.keys.reject {|k| k[0] == '_'}
VALID_SORT_ORDERS = ['desc', 'asc']
def index
order = []
if VALID_SORTABLE_COLUMNS.include?(params[:sort]) && VALID_SORT_ORDERS.include?(params[:order])
order << [params[:sort].to_sym, params[:order].to_sym]
end
# If no valid order is specified, order by date
# If anything else is provided as a sort order, make date a secondary order
if order.empty? || order[0][0] != :created_at
order << [:created_at, :desc]
end
where = {}
where[:username] = current_user.username unless current_user.admin?
start_date = date_param_to_date(params[:log_start_date])
if start_date
where[:created_at] = {'$gte' => start_date}
end
end_date = date_param_to_date(params[:log_end_date])
if end_date
# will create an empty hash if created_at is nil or leave start_date alone if it is there
where[:created_at] ||= {}
where[:created_at].merge!('$lt' => end_date.next_day) # becomes less than midnight the next day
end
@logs = Log.where(where).order_by(order).paginate(:page => params[:page], :per_page => 20)
end
private
def date_param_to_date(date_string)
if date_string && date_string.split('/').length == 3
split_date = date_string.split('/').map(&:to_i)
Date.new(split_date[2], split_date[0], split_date[1])
else
nil
end
end
def validate_authorization!
authorize! :read, Log
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/registrations_controller.rb | app/controllers/registrations_controller.rb | class RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters, if: :devise_controller?
wrap_parameters :user, format: [:json]
unless (APP_CONFIG['allow_user_update'])
before_filter :authorize_user_update
skip_before_filter :require_no_authentication
end
# Need bundle info to display the license information
def new
@bundles = Bundle.all() || []
super
end
def create
@bundles = Bundle.all() || []
super
end
# modified to avoid redirecting if responding via JSON
def update
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
if update_resource(resource, params)
yield resource if block_given?
if is_flashing_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
set_flash_message :notice, flash_key
end
sign_in resource_name, resource, :bypass => true
respond_to do |format|
format.html { redirect_to after_update_path_for(resource) }
format.json { render json: resource }
end
else
clean_up_passwords resource
respond_to do |format|
format.html { render action: "edit" }
format.json { render nothing: true, status: :not_acceptable }
end
end
end
# If this is an AJAX request, just update the attributes; if this is an HTML request, update the attributes unless password or current_password are present.
def update_resource(resource, params)
params = params[resource_name]
if request.xhr? || !(params[:password].present? || params[:current_password].present?)
# remove passwords from params
resource.update_attributes(params.reject { |k, v| %w(password password_confirmation current_password).include? k })
else
resource.update_with_password(params)
end
end
protected
def after_inactive_sign_up_path_for(resource)
'/approval_needed.html'
end
def authorize_user_update
authorize! :manage, resource
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :username, :password, :password_confirmation, :company, :company_url, :registry_name, :registry_id, :npi, :tin) }
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/admin_controller.rb | app/controllers/admin_controller.rb | require 'import_archive_job'
require 'fileutils'
class AdminController < ApplicationController
before_filter :authenticate_user!
before_filter :validate_authorization!
def patients
@patient_count = Record.count
@query_cache_count = HealthDataStandards::CQM::QueryCache.count
@patient_cache_count = PatientCache.count
@provider_count = Provider.count
end
def remove_patients
Record.delete_all
redirect_to action: 'patients'
end
def remove_caches
HealthDataStandards::CQM::QueryCache.delete_all
PatientCache.delete_all
Mongoid.default_session["rollup_buffer"].drop()
redirect_to action: 'patients'
end
def remove_providers
Provider.delete_all
redirect_to action: 'patients'
end
def upload_patients
file = params[:file]
FileUtils.mkdir_p(File.join(Dir.pwd, "tmp/import"))
file_location = File.join(Dir.pwd, "tmp/import")
file_name = "patient_upload" + Time.now.to_i.to_s + rand(1000).to_s
temp_file = File.new(file_location + "/" + file_name, "w")
File.open(temp_file.path, "wb") { |f| f.write(file.read) }
Delayed::Job.enqueue(ImportArchiveJob.new({'file' => temp_file,'user' => current_user}),:queue=>:patient_import)
redirect_to action: 'patients'
end
def upload_providers
file = params[:file]
FileUtils.mkdir_p(File.join(Dir.pwd, "tmp/import"))
file_location = File.join(Dir.pwd, "tmp/import")
file_name = "provider_upload" + Time.now.to_i.to_s + rand(1000).to_s
temp_file = File.new(file_location + "/" + file_name, "w")
File.open(temp_file.path, "wb") { |f| f.write(file.read) }
provider_tree = ProviderTreeImporter.new(File.open(temp_file))
provider_tree.load_providers(provider_tree.sub_providers)
redirect_to action: 'patients'
end
def users
@users = User.all.ordered_by_username
end
def promote
toggle_privilidges(params[:username], params[:role], :promote)
end
def demote
toggle_privilidges(params[:username], params[:role], :demote)
end
def disable
user = User.by_username(params[:username]);
disabled = params[:disabled].to_i == 1
if user
user.update_attribute(:disabled, disabled)
if (disabled)
render :text => "<a href=\"#\" class=\"disable\" data-username=\"#{user.username}\">disabled</span>"
else
render :text => "<a href=\"#\" class=\"enable\" data-username=\"#{user.username}\">enabled</span>"
end
else
render :text => "User not found"
end
end
def approve
user = User.where(:username => params[:username]).first
if user
user.update_attribute(:approved, true)
render :text => "true"
else
render :text => "User not found"
end
end
def update_npi
user = User.by_username(params[:username]);
user.update_attribute(:npi, params[:npi]);
render :text => "true"
end
private
def toggle_privilidges(username, role, direction)
user = User.by_username username
if user
if direction == :promote
user.update_attribute(role, true)
render :text => "Yes - <a href=\"#\" class=\"demote\" data-role=\"#{role}\" data-username=\"#{username}\">revoke</a>"
else
user.update_attribute(role, false)
render :text => "No - <a href=\"#\" class=\"promote\" data-role=\"#{role}\" data-username=\"#{username}\">grant</a>"
end
else
render :text => "User not found"
end
end
def validate_authorization!
authorize! :admin, :users
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery
layout :layout_by_resource
before_filter :set_effective_date
before_filter :check_ssl_used
# lock it down!
check_authorization :unless => :devise_controller?
private
# Overwriting the sign_out redirect path method
def after_sign_out_path_for(resource_or_scope)
"#{Rails.configuration.relative_url_root}/logout.html"
end
def hash_document
d = Digest::SHA1.new
checksum = d.hexdigest(response.body)
Log.create(:username => current_user.username, :event => 'document exported', :checksum => checksum)
end
def layout_by_resource
if devise_controller?
"users"
else
"application"
end
end
rescue_from CanCan::AccessDenied do |exception|
render "public/403", :format=>"html", :status=> 403, :alert => exception.message
end
def set_effective_date(effective_date=nil, persist=false)
if (effective_date)
@effective_date = effective_date
current_user.update_attribute(:effective_date, effective_date) if persist
elsif current_user && current_user.effective_date
@effective_date = current_user.effective_date
else
@effective_date = User::DEFAULT_EFFECTIVE_DATE.to_i
end
@period_start = calc_start(@effective_date)
end
def calc_start(date)
1.year.ago(Time.at(date))
end
def check_ssl_used
unless APP_CONFIG['force_unsecure_communications'] or request.ssl?
redirect_to "#{root_url}no_ssl_warning.html", :alert => "You should be using ssl"
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/queries_controller.rb | app/controllers/api/queries_controller.rb | module Api
class QueriesController < ApplicationController
resource_description do
short 'Queries'
formats ['json']
description <<-QCDESC
This resource is responsible for managing clinical quality measure calculations. Creating a new query will kick
off a new CQM calculation (if it hasn't already been calculated). You can determine the status of ongoing
calculations, force recalculations and see results through this resource.
QCDESC
end
include PaginationHelper
skip_authorization_check
before_filter :authenticate_user!
before_filter :set_pagination_params, :only=>[:patient_results, :patients]
def index
filter = {}
filter["hqmf_id"] = {"$in" => params["measure_ids"]} if params["measure_ids"]
providers = collect_provider_id
filter["filters.providers"] = {"$in" => providers} if providers
render json: QME::QualityReport.where(filter)
end
api :GET, '/queries/:id', "Retrieve clinical quality measure calculation"
param :id, String, :desc => 'The id of the quality measure calculation', :required => true
example '{"DENEX":0,"DENEXCEP":0,"DENOM":5,"IPP":5,"MSRPOPL":0,"NUMER":0, "status":{"state":"completed", ...}, ...}'
description "Gets a clinical quality measure calculation. If calculation is completed, the response will include the results."
def show
@qr = QME::QualityReport.find(params[:id])
authorize! :read, @qr
render json: @qr
end
api :POST, '/queries', "Start a clinical quality measure calculation"
param :measure_id, String, :desc => 'The HQMF id for the CQM to calculate', :required => true
param :sub_id, String, :desc => 'The sub id for the CQM to calculate. This is popHealth specific.', :required => false,:allow_nil => true
param :effective_date, ->(effective_date){ effective_date.present? }, :desc => 'Time in seconds since the epoch for the end date of the reporting period',
:required => true
param :providers, Array, :desc => 'An array of provider IDs to filter the query by', :allow_nil => true
example '{"_id":"52fe409bb99cc8f818000001", "status":{"state":"queued", ...}, ...}'
description <<-CDESC
This action will create a clinical quality measure calculation. If the measure has already been calculated,
it will return the results. If not, it will return the status of the calculation, which can be checked in
the status property of the returned JSON. If it is calculating, then the results may be obtained by the
GET action with the id.
CDESC
def create
options = {}
options[:filters] = build_filter
authorize_providers
options[:effective_date] = params[:effective_date]
options['prefilter'] = build_mr_prefilter if APP_CONFIG['use_map_reduce_prefilter']
qr = QME::QualityReport.find_or_create(params[:measure_id],
params[:sub_id], options)
if !qr.calculated?
qr.calculate( {"oid_dictionary" =>OidHelper.generate_oid_dictionary(qr.measure),
"enable_rationale" => APP_CONFIG['enable_map_reduce_rationale'] || false,
"enable_logging" => APP_CONFIG['enable_map_reduce_logging'] || false}, true)
end
render json: qr
end
api :DELETE, '/queries/:id', "Remove clinical quality measure calculation"
param :id, String, :desc => 'The id of the quality measure calculation', :required => true
def destroy
qr = QME::QualityReport.find(params[:id])
authorize! :delete, qr
qr.destroy
render :status=> 204, :text=>""
end
api :PUT, '/queries/:id/recalculate', "Force a clinical quality measure to recalculate"
param :id, String, :desc => 'The id of the quality measure calculation', :required => true
def recalculate
qr = QME::QualityReport.find(params[:id])
authorize! :recalculate , qr
qr.calculate({"oid_dictionary" =>OidHelper.generate_oid_dictionary(qr.measure_id),
'recalculate' =>true}, true)
render json: qr
end
api :GET, '/queries/:id/patient_results[?population=true|false]',
"Retrieve patients relevant to a clinical quality measure calculation"
param :id, String, :desc => 'The id of the quality measure calculation', :required => true
param :ipp, /true|false/, :desc => 'Ensure patients meet the initial patient population for the measure', :required => false
param :denom, /true|false/, :desc => 'Ensure patients meet the denominator for the measure', :required => false
param :numer, /true|false/, :desc => 'Ensure patients meet the numerator for the measure', :required => false
param :denex, /true|false/, :desc => 'Ensure patients meet the denominator exclusions for the measure', :required => false
param :denexcp, /true|false/, :desc => 'Ensure patients meet the denominator exceptions for the measure', :required => false
param :msrpopl, /true|false/, :desc => 'Ensure patients meet the measure population for the measure', :required => false
param :antinumerator, /true|false/, :desc => 'Ensure patients are not in the numerator but are in the denominator for the measure', :required => false
param_group :pagination, Api::PatientsController
example '[{"_id":"52fe409ef78ba5bfd2c4127f","value":{"DENEX":0,"DENEXCEP":0,"DENOM":1,"IPP":1,"NUMER":1,"antinumerator":0,"birthdate":1276869600.0,"effective_date":1356998340.0,,"first":"Steve","gender":"M","last":"E","measure_id":"40280381-3D61-56A7-013E-6224E2AC25F3","medical_record_id":"ce83c561f62e245ad4e0ca648e9de0dd","nqf_id":"0038","patient_id":"52fbbf34b99cc8a728000068"}},...]'
description <<-PRDESC
This action returns an array of patients that have results calculated for this clinical quality measure. The list can be restricted
to specific populations, such as only patients that have made it into the numerator by passing in a query parameter for a particular
population. Results are paginated.
PRDESC
def patient_results
qr = QME::QualityReport.find(params[:id])
authorize! :read, qr
# this returns a criteria object so we can filter it additionally as needed
results = qr.patient_results
render json: paginate(patient_results_api_query_url(qr),results.where(build_patient_filter).order_by([:last.asc, :first.asc]))
end
def patients
qr = QME::QualityReport.find(params[:id])
authorize! :read, qr
# this returns a criteria object so we can filter it additionally as needed
results = qr.patient_results
ids = paginate(patients_api_query_url(qr),results.where(build_patient_filter).order_by([:last.asc, :first.asc])).collect{|r| r["value.medical_record_id"]}
render :json=> Record.where({:medical_record_number.in => ids})
end
private
def build_filter
@filter = params.select { |k, v| %w(providers).include? k }.to_options
end
def authorize_providers
providers = @filter[:providers] || []
if !providers.empty?
providers.each do |p|
provider = Provider.find(p)
authorize! :read, provider
end
else
#this is hacky and ugly but cancan will allow just the
# class Provider to pass for a simple user so providing
#an empty Provider with no NPI number gets around this
authorize! :read, Provider.new
end
end
def build_mr_prefilter
measure = HealthDataStandards::CQM::Measure.where({"hqmf_id" => params[:measure_id], "sub_id"=>params[:sub_id]}).first
measure.prefilter_query!(params[:effective_date].to_i)
end
def build_patient_filter
patient_filter = {}
patient_filter["value.IPP"]= {"$gt" => 0} if params[:ipp] == "true"
patient_filter["value.DENOM"]= {"$gt" => 0} if params[:denom] == "true"
patient_filter["value.NUMER"]= {"$gt" => 0} if params[:numer] == "true"
patient_filter["value.DENEX"]= {"$gt" => 0} if params[:denex] == "true"
patient_filter["value.DENEXCEP"]= {"$gt" => 0} if params[:denexcep] == "true"
patient_filter["value.MSRPOPL"]= {"$gt" => 0} if params[:msrpopl] == "true"
patient_filter["value.antinumerator"]= {"$gt" => 0} if params[:antinumerator] == "true"
patient_filter["value.provider_performances.provider_id"]= BSON::ObjectId.from_string(params[:provider_id]) if params[:provider_id]
patient_filter
end
def collect_provider_id
params[:providers] || Provider.where({:npi.in => params[:npis] || []}).to_a
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/measures_controller.rb | app/controllers/api/measures_controller.rb | require 'measures/loader.rb'
require 'hds/measure.rb'
module Api
class MeasuresController < ApplicationController
resource_description do
short 'Measures'
formats ['json']
description "This resource allows for the management of clinical quality measures in the popHealth application."
end
include PaginationHelper
before_filter :authenticate_user!
before_filter :validate_authorization!
before_filter :set_pagination_params, :only=> :index
before_filter :create_filter , :only => :index
before_filter :update_metadata_params, :only => :update_metadata
api :GET, "/measures", "Get a list of measures"
param_group :pagination, Api::PatientsController
def index
measures = HealthDataStandards::CQM::Measure.where(@filter)
render json: paginate(api_measures_url, measures), each_serializer: HealthDataStandards::CQM::MeasureSerializer
end
api :GET, "/measures/:id", "Get an individual clinical quality measure"
param :id, String, :desc => 'The HQMF id for the CQM to calculate', :required => true
param :sub_id, String, :desc => 'The sub id for the CQM to calculate. This is popHealth specific.', :required => false
def show
measure = HealthDataStandards::CQM::Measure.where({"hqmf_id" => params[:id], "sub_id"=>params[:sub_id]}).first
render :json=> measure
end
api :POST, "/measures", "Load a measure into popHealth"
description "The uploaded measure must be in the popHealth JSON measure format. This will not accept HQMF definitions of measures."
def create
authorize! :create, HealthDataStandards::CQM::Measure
measure_details = {
'type'=>params[:measure_type],
'episode_of_care'=>params[:calculation_type] == 'episode',
'category'=> params[:category].empty? ? "miscellaneous" : params[:category],
'lower_is_better'=> params[:lower_is_better]
}
ret_value = {}
hqmf_document = Measures::Loader.parse_model(params[:measure_file].tempfile.path)
if measure_details["episode_of_care"]
Measures::Loader.save_for_finalization(hqmf_document)
ret_value= {episode_ids: hqmf_document.specific_occurrence_source_data_criteria().collect{|dc| {id: dc.id, description: dc.description}},
hqmf_id: hqmf_document.hqmf_id,
vsac_username: params[:vsac_username],
vsac_password: params[:vsac_password],
category: measure_details["category"],
lower_is_better: measure_details[:lower_is_better],
hqmf_document: hqmf_document
}
else
Measures::Loader.generate_measures(hqmf_document,params[:vsac_username],params[:vsac_password],measure_details)
end
render json: ret_value
rescue => e
render text: e.to_s, status: 500
end
api :DELETE, '/measures/:id', "Remove a clinical quality measure from popHealth"
param :id, String, :desc => 'The HQMF id for the CQM to calculate', :required => true
description "Removes the measure from popHealth. It also removes any calculations for that measure."
def destroy
authorize! :delete, HealthDataStandards::CQM::Measure
measure = HealthDataStandards::CQM::Measure.where({"hqmf_id" => params[:id]})
#delete all of the pateint and query cache entries for the measure
HealthDataStandards::CQM::PatientCache.where({"value.measure_id" => params[:id]}).destroy
HealthDataStandards::CQM::QueryCache.where({"measure_id" => params[:id]}).destroy
measure.destroy
render :status=>204, :text=>""
end
def update_metadata
authorize! :update, HealthDataStandards::CQM::Measure
measures = HealthDataStandards::CQM::Measure.where({ hqmf_id: params[:hqmf_id]})
measures.each do |m|
m.update_attributes(params[:measure])
m.save
end
render json: measures, each_serializer: HealthDataStandards::CQM::MeasureSerializer
rescue => e
render text: e.to_s, status: 500
end
def finalize
measure_details = {
'episode_ids'=>params[:episode_ids],
'category' => params[:category],
'measure_type' => params[:measure_type],
'lower_is_better' => params[:lower_is_better]
}
Measures::Loader.finalize_measure(params[:hqmf_id],params[:vsac_username],params[:vsac_password],measure_details)
measure = HealthDataStandards::CQM::Measure.where({hqmf_id: params[:hqmf_id]}).first
render json: measure, serializer: HealthDataStandards::CQM::MeasureSerializer
rescue => e
render text: e.to_s, status: 500
end
private
def validate_authorization!
authorize! :read, HealthDataStandards::CQM::Measure
end
def create_filter
measure_ids = params[:measure_ids]
@filter = measure_ids.nil? || measure_ids.empty? ? {} : {:hqmf_id.in => measure_ids}
end
def update_metadata_params
params[:measure][:lower_is_better] = nil if params[:measure][:lower_is_better].blank?
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/providers_controller.rb | app/controllers/api/providers_controller.rb | module Api
class ProvidersController < ApplicationController
resource_description do
short 'Providers'
formats ['json']
description <<-PRCDESC
This resource allows for the management of providers in popHealth
popHealth assumes that providers are in a hierarchy. This resource allows users
to see the hierarchy of providers
PRCDESC
end
include PaginationHelper
# load resource must be before authorize resource
load_resource except: %w{index create new}
authorize_resource
respond_to :json
before_filter :authenticate_user!
api :GET, "/providers", "Get a list of providers. Returns all providers that the user has access to."
param_group :pagination, Api::PatientsController
def index
@providers = paginate(api_providers_url, Provider.order_by([:"cda_identifiers.sortable_extension", :asc]))
authorize_providers(@providers)
render json: @providers
end
api :GET, "/providers/:id", "Get an individual provider"
param :id, String, :desc => "Provider ID", :required => true
description <<-SDESC
This will return an individual provider. It will include the id and name of its parent, if it
has a parent. Children providers one level deep will be included in the children property
if any children for this provider exist.
SDESC
example <<-EXAMPLE
{
"_id": "5331db9575efe558ad000bc9",
"address": "1601 S W Archer Road Gainesville FL 32608",
"cda_identifiers": [
{
"_id": "5331db9575efe558ad000bca",
"extension": "573",
"root": "Division"
}
],
"family_name": null,
"given_name": "North Florida\/South Georgia HCS-Gainesville",
"level": null,
"parent_id": "5331db9575efe558ad000bc7",
"parent_ids": [
"5331db9475efe558ad0008da",
"5331db9575efe558ad000b8d",
"5331db9575efe558ad000bc7"
],
"phone": null,
"specialty": null,
"team_id": null,
"title": null,
"parent": {
"_id": "5331db9575efe558ad000bc7",
"address": "1601 S W Archer Road Gainesville FL 32608",
"cda_identifiers": [
{
"_id": "5331db9575efe558ad000bc8",
"extension": "573",
"root": "Facility"
}
],
"family_name": null,
"given_name": "North Florida\/South Georgia HCS-Gainesville",
"level": null,
"parent_id": "5331db9575efe558ad000b8d",
"parent_ids": [
"5331db9475efe558ad0008da",
"5331db9575efe558ad000b8d"
],
"phone": null,
"specialty": null,
"team_id": null,
"title": null
}
}
EXAMPLE
def show
provider_json = @provider.as_json
provider_json[:parent] = Provider.find(@provider.parent_id) if @provider.parent_id
provider_json[:children] = @provider.children if @provider.children.present?
render json: provider_json
end
api :POST, "/providers", "Create a new provider"
def create
@provider = Provider.create(params[:provider])
render json: @provider
end
api :PUT, "/providers/:id", "Update a provider"
param :id, String, :desc => "Provider ID", :required => true
def update
@provider.update_attributes!(params[:provider])
render json: @provider
end
def new
render json: Provider.new
end
api :DELETE, "/providers/:id", "Remove an individual provider"
param :id, String, :desc => "Provider ID", :required => true
def destroy
@provider.destroy
render json: nil, status: 204
end
private
def authorize_providers(providers)
providers.each do |p|
authorize! :read, p
end
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/patients_controller.rb | app/controllers/api/patients_controller.rb | module Api
class PatientsController < ApplicationController
resource_description do
short 'Patients'
description <<-PCDESC
This resource allows for the management of patient records in the popHealth application.
Patient records can be inserted into popHealth in QRDA Category I format through this resource.
Additionally, patient information may be retrieved from popHealth. This includes popHealth's
internal representation of a patient as well as results for clinical quality measure calculations
for a particular patient.
Ids used for patients by this resource are the MongoDB identifier for the patient, not the
patient's medical record number.
PCDESC
end
include PaginationHelper
respond_to :json
before_filter :authenticate_user!
before_filter :validate_authorization!
before_filter :load_patient, :only => [:show, :delete, :toggle_excluded, :results]
before_filter :set_pagination_params, :only => :index
before_filter :set_filter_params, :only => :index
def_param_group :pagination do
param :page, /\d+/
param :per_page, /\d+/
end
api :GET, "/patients", "Get a list of patients"
param_group :pagination
formats ['json']
def index
records = Record.where(@query)
respond_with paginate(api_patients_url,records)
end
api :GET, "/patients/:id[?include_results=:include_results]", "Retrieve an individual patient"
formats ['json']
param :id, String, :desc => "Patient ID", :required => true
param :include_results, String, :desc => "Include measure calculation results", :required => false
example '{"_id":"52fbbf34b99cc8a728000068","birthdate":1276869600,"first":"John","gender":"M","last":"Peters","encounters":[{...}], ...}'
def show
json_methods = [:language_names]
json_methods << :cache_results if params[:include_results]
json = @patient.as_json({methods: json_methods})
provider_list = @patient.provider_performances.map{ |p| p.provider}
provider_list.each do |prov|
if prov
if prov.leaf?
json['provider_name'] = prov.given_name
end
end
end
if results = json.delete('cache_results')
json['measure_results'] = results_with_measure_metadata(results)
end
Log.create(:username => current_user.username,
:event => 'patient record viewed',
:medical_record_number => @patient.medical_record_number)
render :json => json
end
api :POST, "/patients", "Load a patient into popHealth"
formats ['xml']
param :file, nil, :desc => "The QRDA Cat I file", :required => true
description "Upload a QRDA Category I document for a patient into popHealth."
def create
authorize! :create, Record
success = HealthDataStandards::Import::BulkRecordImporter.import(params[:file])
if success
Log.create(:username => @current_user.username, :event => 'record import')
render status: 201, text: 'Patient Imported'
else
render status: 500, text: 'Patient record did not save properly'
end
end
def toggle_excluded
# TODO - figure out security constraints around manual exclusions -- this should probably be built around
# the security constraints for queries
ManualExclusion.toggle!(@patient, params[:measure_id], params[:sub_id], params[:rationale], current_user)
redirect_to :controller => :measures, :action => :patients, :id => params[:measure_id], :sub_id => params[:sub_id]
end
api :DELETE, '/records/:id', "Remove a patient from popHealth"
param :id, String, :desc => 'The id of the patient', :required => true
def destroy
authorize! :delete, @patient
@patient.destroy
render :status=> 204, text=> ""
end
api :GET, "/patients/:id/results", "Retrieve the CQM calculation results for a individual patient"
formats ['json']
param :id, String, :desc => "Patient ID", :required => true
example '[{"DENOM":1.0,"NUMER":1.0,"DENEXCEP":0.0,"DENEX":0.0",measure_id":"40280381-3D61-56A7-013E-6224E2AC25F3","nqf_id":"0038","effective_date":1356998340.0,"measure_title":"Childhood Immunization Status",...},...]'
def results
render :json=> results_with_measure_metadata(@patient.cache_results(params))
end
private
def load_patient
@patient = Record.find(params[:id])
authorize! :read, @patient
end
def validate_authorization!
authorize! :read, Record
end
def set_filter_params
@query = {}
if params[:quality_report_id]
@quality_report = QME::QualityReport.find(params[:quality_report_id])
authorize! :read, @quality_report
@query["provider.npi"] = {"$in" => @quality_report.filters["providers"]}
elsif current_user.admin?
else
@query["provider.npi"] = current_user.npi
end
@order = params[:order] || [:last.asc, :first.asc]
end
def results_with_measure_metadata(results)
results.to_a.map do |result|
hqmf_id = result['value']['measure_id']
sub_id = result['value']['sub_id']
measure = HealthDataStandards::CQM::Measure.where("hqmf_id" => hqmf_id, "sub_id" => sub_id).only(:title, :subtitle, :name).first
result['value'].merge(measure_title: measure.title, measure_subtitle: measure.subtitle)
end
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/reports_controller.rb | app/controllers/api/reports_controller.rb | module Api
class ReportsController < ApplicationController
resource_description do
short 'Reports'
formats ['xml']
description <<-RCDESC
This resource is responsible for the generation of QRDA Category III reports from clincial
quality measure calculations.
RCDESC
end
before_filter :authenticate_user!
skip_authorization_check
api :GET, '/reports/qrda_cat3.xml', "Retrieve a QRDA Category III document"
param :measure_ids, Array, :desc => 'The HQMF ID of the measures to include in the document', :required => false
param :effective_date, String, :desc => 'Time in seconds since the epoch for the end date of the reporting period',
:required => false
param :provider_id, String, :desc => 'The Provider ID for CATIII generation'
description <<-CDESC
This action will generate a QRDA Category III document. If measure_ids and effective_date are not provided,
the values from the user's dashboard will be used.
CDESC
def cat3
measure_ids = params[:measure_ids] ||current_user.preferences["selected_measure_ids"]
filter = measure_ids=="all" ? {} : {:hqmf_id.in =>measure_ids}
exporter = HealthDataStandards::Export::Cat3.new
effective_date = params["effective_date"] || current_user.effective_date || Time.gm(2012, 12, 31)
end_date = Time.at(effective_date.to_i)
provider = provider_filter = nil
if params[:provider_id].present?
provider = Provider.find(params[:provider_id])
provider_filter = {}
provider_filter['filters.providers'] = params[:provider_id] if params[:provider_id].present?
end
render xml: exporter.export(HealthDataStandards::CQM::Measure.top_level.where(filter),
generate_header(provider),
effective_date.to_i,
end_date.years_ago(1),
end_date, provider_filter), content_type: "attachment/xml"
end
api :GET, "/reports/cat1/:id/:measure_ids"
formats ['xml']
param :id, String, :desc => "Patient ID", :required => true
param :measure_ids, String, :desc => "Measure IDs", :required => true
param :effective_date, String, :desc => 'Time in seconds since the epoch for the end date of the reporting period',
:required => false
description <<-CDESC
This action will generate a QRDA Category I Document. Patient ID and measure IDs (comma separated) must be provided. If effective_date is not provided,
the value from the user's dashboard will be used.
CDESC
def cat1
exporter = HealthDataStandards::Export::Cat1.new
patient = Record.find(params[:id])
measure_ids = params["measure_ids"].split(',')
measures = HealthDataStandards::CQM::Measure.where(:hqmf_id.in => measure_ids)
end_date = params["effective_date"] || current_user.effective_date || Time.gm(2012, 12, 31)
start_date = end_date.years_ago(1)
render xml: exporter.export(patient, measures, start_date, end_date)
end
private
def generate_header(provider)
header = Qrda::Header.new(APP_CONFIG["cda_header"])
header.identifier.root = UUID.generate
header.authors.each {|a| a.time = Time.now}
header.legal_authenticator.time = Time.now
header.performers << provider
header
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/admin/caches_controller.rb | app/controllers/api/admin/caches_controller.rb | module Api
module Admin
class CachesController < ApplicationController
resource_description do
resource_id 'Admin::Caches'
short 'Caches Admin'
formats ['json']
description "This resource allows for administrative tasks to be performed on the cache via the API."
end
before_filter :authenticate_user!
before_filter :validate_authorization!
api :GET, "/admin/caches/count", "Return count of caches in the database."
example '{"query_cache_count":56, "patient_cache_count":100}'
def count
json = {}
json['query_cache_count'] = HealthDataStandards::CQM::QueryCache.count
json['patient_cache_count'] = PatientCache.count
render :json => json
end
api :DELETE, "/admin/caches", "Empty all caches in the database."
def destroy
HealthDataStandards::CQM::QueryCache.delete_all
PatientCache.delete_all
render status: 200, text: 'Server caches have been emptied.'
end
private
def validate_authorization!
authorize! :admin, :users
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/admin/users_controller.rb | app/controllers/api/admin/users_controller.rb | module Api
module Admin
class UsersController < ApplicationController
resource_description do
resource_id 'Admin::Users'
short 'Users Admin'
formats ['json']
description "This resource allows for administrative tasks to be performed on users via the API."
end
include PaginationHelper
respond_to :json
before_filter :authenticate_user!
before_filter :validate_authorization!
def_param_group :pagination do
param :page, /\d+/
param :per_page, /\d+/
end
api :GET, "/admin/users", "Get a list of users."
param_group :pagination
formats ['json']
example '[{"_id":"53bab4134d4d31c98d0a0000","admin":null,"agree_license":null,"approved":false,"company":"","company_url":"","disabled":false,"effective_date":null,"email":"email@email.com","first_name":"fname","last_name":"lname","npi":"","registry_id":"","registry_name":"","staff_role":true,"tin":"","username":"user"}]'
description "Returns a paginated list of all users in the database."
def index
users = User.all.ordered_by_username
render json: paginate(admin_users_path,users)
end
api :POST, "/admin/users/:id/promote", "Promote a user to provided role."
param :id, String, :desc => 'The ID of the user to promote.', :required => true
param :role, String, :desc => 'The role to promote the user to, for example staff_role or admin.', :required => true
def promote
toggle_privileges(params[:id], params[:role], :promote)
end
api :POST, "/admin/users/:id/demote", "Demote a user from provided role."
param :id, String, :desc => 'The ID of the user to demote.', :required => true
param :role, String, :desc => 'The role to demote the user from, for example staff_role or admin.', :required => true
def demote
toggle_privileges(params[:id], params[:role], :demote)
end
api :GET, "/admin/users/:id/enable", "Enable a users account."
param :id, String, :desc => 'The ID of the user to enable.', :required => true
def enable
toggle_enable_disable(params[:id], 1)
end
api :GET, "/admin/users/:id/disable", "Disable a users account."
param :id, String, :desc => 'The ID of the user to disable.', :required => true
def disable
toggle_enable_disable(params[:id], 0)
end
api :GET, "/admin/users/:id/approve", "Approve a users account."
param :id, String, :desc => 'The ID of the user to approve.', :required => true
def approve
update_user(params[:id], :approved, true, "approved")
end
api :POST, "/admin/users/:id/update_npi", "Update users associated NPI."
param :id, String, :desc => 'The ID of the user to update.', :required => true
param :npi, String, :desc => 'The new NPI to assign the user to.', :required => true
def update_npi
update_user(params[:id], :npi, params[:npi], "updated")
end
private
def toggle_enable_disable(user_id, enable)
enable = enable == 1
if enable
update_user(user_id, :disabled, false, "enabled")
else
update_user(user_id, :disabled, true, "disabled")
end
end
def toggle_privileges(user_id, role, direction)
if direction == :promote
update_user(user_id, role, true, "promoted")
else
update_user(user_id, role, false, "demoted")
end
end
def update_user(user_id, field, value, action)
user = User.where(:id => user_id).first
if user
user.update_attribute(field, value)
render status: 200, text: "User has been #{action}."
else
render status: 404, text: "User not found."
end
end
def validate_authorization!
authorize! :admin, :users
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/admin/providers_controller.rb | app/controllers/api/admin/providers_controller.rb | module Api
module Admin
class ProvidersController < ApplicationController
resource_description do
resource_id 'Admin::Providers'
short 'Providers Admin'
formats ['json']
description "This resource allows for administrative tasks to be performed on providers via the API."
end
before_filter :authenticate_user!
before_filter :validate_authorization!
api :GET, "/admin/providers/count", "Get count of providers in the database"
formats ['json']
example '{"provider_count":2}'
def count
json = {}
json['provider_count'] = Provider.count
render :json => json
end
api :POST, "/admin/providers", "Upload an opml file of providers."
param :file, nil, :desc => 'The ompl file of providers to upload.', :required => true
def create
file = params[:file]
FileUtils.mkdir_p(File.join(Dir.pwd, "tmp/import"))
file_location = File.join(Dir.pwd, "tmp/import")
file_name = "provider_upload" + Time.now.to_i.to_s + rand(1000).to_s
temp_file = File.new(file_location + "/" + file_name, "w")
File.open(temp_file.path, "wb") { |f| f.write(file.read) }
provider_tree = ProviderTreeImporter.new(File.open(temp_file))
provider_tree.load_providers(provider_tree.sub_providers)
render status: 200, text: 'Provider opml has been uploaded.'
end
api :DELETE, "/admin/providers", "Delete all providers in the database."
def destroy
Provider.delete_all
render status: 200, text: 'Provider records successfully removed from database.'
end
private
def validate_authorization!
authorize! :admin, :users
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/controllers/api/admin/patients_controller.rb | app/controllers/api/admin/patients_controller.rb | module Api
module Admin
class PatientsController < ApplicationController
resource_description do
resource_id 'Admin::Patients'
short 'Patients Admin'
formats ['json']
description "This resource allows for the management of clinical quality measures in the popHealth application."
end
before_filter :authenticate_user!
before_filter :validate_authorization!
skip_before_action :verify_authenticity_token
api :GET, "/patients/count", "Get count of patients in the database"
formats ['json']
example '{"patient_count":56}'
def count
json = {}
json['patient_count'] = Record.count
render :json => json
end
api :POST, "/admin/patients", "Upload a zip file of patients."
param :file, nil, :desc => 'The zip file of patients to upload.', :required => true
def create
file = params[:file]
FileUtils.mkdir_p(File.join(Dir.pwd, "tmp/import"))
file_location = File.join(Dir.pwd, "tmp/import")
file_name = "patient_upload" + Time.now.to_i.to_s + rand(1000).to_s
temp_file = File.new(file_location + "/" + file_name, "w")
File.open(temp_file.path, "wb") { |f| f.write(file.read) }
Delayed::Job.enqueue(ImportArchiveJob.new({'file' => temp_file,'user' => current_user}),:queue=>:patient_import)
render status: 200, text: 'Patient file has been uploaded.'
end
api :DELETE, "/admin/patients", "Delete all patients in the database."
def destroy
Record.delete_all
render status: 200, text: 'Patient records successfully removed from database.'
end
private
def validate_authorization!
authorize! :admin, :users
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/language.rb | app/models/language.rb | class Language
include Mongoid::Document
field :name, type: String
field :order, type: Integer
field :codes, type: Array
scope :ordered, -> { asc(:order) }
scope :selected, ->(language_ids) { any_in(:_id => language_ids)}
scope :selected_or_all, ->(language_ids) { language_ids.nil? || language_ids.empty? ? Language.all : Language.selected(language_ids) }
scope :by_code, ->(codes) { any_in(codes: codes)}
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/preference.rb | app/models/preference.rb | class Preference
include Mongoid::Document
field :selected_measure_ids, type: Array, default: []
field :mask_phi_data, type: Boolean, default: false
field :should_display_circle_visual, type: Boolean, default: true
field :population_chart_scaled_to_IPP, type: Boolean, default: false
belongs_to :user
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/bundle.rb | app/models/bundle.rb | class Bundle
include Mongoid::Document
field :title, type: String
field :effective_date, type: Integer
field :version, type: String
field :license, type: String
field :measures, type: Array
field :exported, type: String
field :extensions, type: Array
def license
read_attribute(:license)
.gsub(/\\("|')/,'\1') # Remove \ characters from in front of ' or " in the bundle.
.gsub(/\\n|",$/,' ') # Remove \n from printing out and get rid of ", at end of bundle, replace with space.
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/ability.rb | app/models/ability.rb | class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
# The first argument to `can` is the action you are giving the user permission to do.
# If you pass :manage it will apply to every action. Other common actions here are
# :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on. If you pass
# :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
#
# The third argument is an optional hash of conditions to further filter the objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities
user ||= User.new
if user.admin?
can :manage, :all
# can [:create,:delete], Record
# can :manage, Provider
# can [:read, :recalculate,:create, :deleted], QME::QualityReport
# can [:create,:delete], HealthDataStandards::CQM::Measure
elsif user.staff_role?
can :read, HealthDataStandards::CQM::Measure
can :read, Record
can :manage, Provider
can :manage, :providers
can :manage, User, id: user.id
cannot :manage, User unless APP_CONFIG['allow_user_update']
can [:read, :delete, :recalculate,:create] , QME::QualityReport
elsif user.id
can :read, Record do |patient|
patient.providers.map(&:npi).include?(user.npi)
end
can [:read,:delete, :recalculate, :create], QME::QualityReport do |qr|
provider = Provider.by_npi(user.npi).first
provider ? (qr.filters || {})["providers"].include?(provider.id) : false
end
can :read, HealthDataStandards::CQM::Measure
can :read, Provider do |pv|
user.npi && (pv.npi == user.npi)
end
can :manage, User, id: user.id
cannot :manage, User unless APP_CONFIG['allow_user_update']
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/log.rb | app/models/log.rb | class Log
include Mongoid::Document
include Mongoid::Timestamps
field :username, :type => String
field :event, :type => String
field :description, :type => String
field :medical_record_number, :type => String
field :checksum, :type => String
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/ethnicity.rb | app/models/ethnicity.rb | class Ethnicity
include Mongoid::Document
field :name, type: String
field :order, type: Integer
field :codes, type: Array
scope :from_code, ->(code) {where("codes" => code)}
scope :ordered, -> { asc(:order) }
scope :selected, ->(ethnicity_ids) { any_in(:_id => ethnicity_ids)}
scope :selected_or_all, ->(ethnicity_ids) { ethnicity_ids.nil? || ethnicity_ids.empty? ? Ethnicity.all : Ethnicity.selected(ethnicity_ids) }
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/manual_exclusion.rb | app/models/manual_exclusion.rb | class ManualExclusion
include Mongoid::Document
store_in collection: :manual_exclusions
field :measure_id, type: String
field :sub_id, type: String
field :medical_record_id, type: String
field :rationale, type: String
field :created_at, type: Date
belongs_to :user
scope :selected, ->(medical_record_ids) { any_in(:medical_record_id => medical_record_ids)}
scope :for_record, ->(patient) {where("medical_record_id" => patient.medical_record_number)}
def self.toggle!(patient, measure_id, sub_id, rationale, user)
existing = ManualExclusion.where({:medical_record_id => patient.medical_record_number}).and({:measure_id => measure_id}).and({:sub_id => sub_id}).first
if existing
Log.create(:username => user.username, :event => 'manual exclusion revoked', :description => rationale, :medical_record_number => patient.medical_record_number)
existing.destroy
MONGO_DB['patient_cache'].find({'value.measure_id'=>measure_id, 'value.sub_id'=>sub_id, 'value.medical_record_id'=>patient.medical_record_number }).update({'$set'=>{'value.manual_exclusion'=>false}}, :multi=>true)
else
Log.create(:username => user.username, :event => 'manual exclusion envoked', :description => rationale, :medical_record_number => patient.medical_record_number)
ManualExclusion.create!({:medical_record_id => patient.medical_record_number, :measure_id => measure_id, :sub_id => sub_id, :rationale => rationale, user: user, created_at: Time.now})
MONGO_DB['patient_cache'].find({'value.measure_id'=>measure_id, 'value.sub_id'=>sub_id, 'value.medical_record_id'=>patient.medical_record_number }).update({'$set'=>{'value.manual_exclusion'=>true}}, :multi=>true)
end
HealthDataStandards::CQM::QueryCache.where({:measure_id => measure_id}).and({:sub_id => sub_id}).destroy_all
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/organization.rb | app/models/organization.rb | class Organization
# include Mongoid::Document
# include Mongoid::Timestamps
# #include Mongoid::Tree
# # include Mongoid::Tree::Ordering
# # include Mongoid::Tree::Traversal
# field :name, type: String
# field :type, type: String
# field :npi, type: String
# has_many :providers
# def all_providers
# provs = self.descendants.collect do |d|
# d.providers
# end
# provs << self.providers
# provs.flatten!.uniq!
# end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/race.rb | app/models/race.rb | class Race
include Mongoid::Document
field :name, type: String
field :order, type: Integer
field :codes, type: Array
scope :from_code, ->(code) {where("codes" => code)}
scope :ordered, -> { asc(:username) }
scope :selected, ->(race_ids) { any_in(:_id => race_ids)}
scope :selected_or_all, ->(race_ids) { race_ids.nil? || race_ids.empty? ? Race.all : Race.selected(race_ids) }
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/patient_cache.rb | app/models/patient_cache.rb | class PatientCache
include Mongoid::Document
store_in collection: :patient_cache
field :first, type: String
field :last, type: String
field :patient_id, type: String
field :birthdate, type: Integer
field :gender, type: String
scope :by_provider, ->(provider, effective_date) { where({'value.provider_performances.provider_id' => provider.id, 'value.effective_date'=>effective_date}) }
scope :outliers, ->(patient) {where({'value.patient_id'=>patient.id})}
MATCH = {'$match' => {'value.measure_id' => "8A4D92B2-397A-48D2-0139-9BB3331F4C02", "value.sub_id" => "a"}}
SUM = {'$group' => {
"_id" => "$value.measure_id", # we don't really need this, but Mongo requires that we group
"population" => {"$sum" => "$value.population"},
"denominator" => {"$sum" => "$value.denominator"},
"numerator" => {"$sum" => "$value.numerator"},
"antinumerator" => {"$sum" => "$value.antinumerator"},
"exclusions" => {"$sum" => "$value.exclusions"},
"denexcep" => {"$sum" => "$value.denexcep"},
"considered" => {"$sum" => 1}
}}
REWIND = {'$group' => {"_id" => "$_id", "value" => {"$first" => "$value"}}}
def self.provider
aggregate({"$match"=>
{"value.measure_id"=>"8A4D92B2-3A00-2A25-013A-23015AD43373",
"value.sub_id"=>nil,
"value.effective_date"=>1293840000,
"value.test_id"=>nil,
"value.manual_exclusion"=>{"$in"=>[nil, false]}}},
{"$project"=>
{"value"=>1, "providers"=>"$value.provider_performances.provider_id"}},
{"$unwind"=>"$providers"},
{"$match"=>
{"$or"=>
[{"providers"=> BSON::ObjectId.from_string("50a64aa68898e5b4b2000001")},
{"providers"=> BSON::ObjectId.from_string("50a64aa68898e5b4b2000003")},
{"providers"=> BSON::ObjectId.from_string("50a55a8e8898e5d400000005")},
{"providers"=> BSON::ObjectId.from_string("50a64aa68898e5b4b2000007")},
{"providers"=> BSON::ObjectId.from_string("50a64aa68898e5b4b2000009")}]}})
end
def self.languages
# aggregate({'$project' => {'value' => 1, 'languages' => "$value.languages"}},
# {'$unwind' => "$languages"},
# {'$project' => {'value' => 1, 'languages' => {'$substr' => ['$languages', 0, 2]}}},
# {'$match' => {'$or' => [{'languages' => "en"}, {'languages' => "fr"}]}},
# REWIND}
# )
end
def self.aggregate(*pipeline)
Mongoid.default_session.command(aggregate: 'patient_cache', pipeline: pipeline)['result']
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/models/user.rb | app/models/user.rb | require 'uniq_validator'
require 'protected_attributes'
class User
include ActiveModel::MassAssignmentSecurity
include Mongoid::Document
after_initialize :build_preferences, unless: Proc.new { |user| user.preferences.present? }
before_save :denullify_arrays
before_create :set_defaults
DEFAULT_EFFECTIVE_DATE = Time.gm(2011, 1, 1)
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:username]
## Database authenticatable
field :encrypted_password, :type => String
## Recoverable
field :reset_password_token, :type => String
field :reset_password_sent_at, :type => Time
## Rememberable
field :remember_created_at, :type => Time
## Trackable
field :sign_in_count, :type => Integer
field :current_sign_in_at, :type => Time
field :last_sign_in_at, :type => Time
field :current_sign_in_ip, :type => String
field :last_sign_in_ip, :type => String
:remember_created_at
:reset_password_token
:reset_password_sent_at
:sign_in_count
:current_sign_in_at
:last_sign_in_at
:current_sign_in_ip
:last_sign_in_ip
:effective_date
field :first_name, type: String
field :last_name, type: String
field :username, type: String
field :email, type: String
field :company, type: String
field :company_url, type: String
field :registry_id, type: String
field :registry_name, type: String
field :npi, :type => String
field :tin, :type => String
field :agree_license, type: Boolean
field :effective_date, type: Integer
field :admin, type: Boolean
field :approved, type: Boolean
field :staff_role, type: Boolean
field :disabled, type: Boolean
has_one :preferences, class_name: 'Preference'
scope :ordered_by_username, -> { asc(:username) }
attr_protected :admin, :approved, :disabled, :encrypted_password, :remember_created_at, :reset_password_token, :reset_password_sent_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip, :effective_date
accepts_nested_attributes_for :preferences
validates_presence_of :first_name, :last_name
validates_uniqueness_of :username
validates_uniqueness_of :email
validates_acceptance_of :agree_license, :accept => true
validates :email, presence: true, length: {minimum: 3, maximum: 254}, format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i}
validates :username, :presence => true, length: {minimum: 3, maximum: 254}
def set_defaults
self.staff_role ||= APP_CONFIG["default_user_staff_role"]
self.approved ||= APP_CONFIG["default_user_approved"]
true
end
# replace nil with [] when it should be an array; see https://github.com/rails/rails/issues/8832
def denullify_arrays
# if self.preferences[:selected_measure_ids] == nil
# binding.pry
# end
self.preferences["selected_measure_ids"] ||= []
# puts self.preferences[:selected_measure_ids]
end
def active_for_authentication?
super && approved? && !disabled?
end
def inactive_message
if !approved?
:not_approved
else
super # Use whatever other message
end
end
# =============
# = Accessors =
# =============
def full_name
"#{first_name} #{last_name}"
end
# ===========
# = Finders =
# ===========
def self.by_username(username)
where(username: username).first
end
def self.by_email(email)
where(email: email).first
end
# =============
# = Modifiers =
# =============
def grant_admin
update_attribute(:admin, true)
update_attribute(:approved, true)
end
def approve
update_attribute(:approved, true)
end
def revoke_admin
update_attribute(:admin, false)
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/app/mailers/notifier.rb | app/mailers/notifier.rb | class Notifier < ActionMailer::Base
default :from => "noreply@pophealth.org"
def reset_password(user)
@user = user
mail(:to => user.email, :subject => 'popHealth Account Password Reset')
end
def verify(user)
@user = user
mail(:to => user.email, :subject => 'popHealth Account Verification')
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/vendor/assets/components/font-awesome/src/_plugins/icon_page_generator.rb | vendor/assets/components/font-awesome/src/_plugins/icon_page_generator.rb | ##
# Create individual pages for each icon in the FontAwesome set
require 'yaml'
require 'debugger'
module Jekyll
class IconPage < Page
##
# Take a single icon and render a page for it.
def initialize(site, base, dir, icon)
@site = site
@base = base
@dir = dir
@name = "#{icon.id}.html"
@icon = icon
self.process(@name)
self.read_yaml(File.join(base, site.config['layouts']), site.config['icon_layout'])
self.data['icon'] = icon
self.data['title'] = "icon-#{icon.id}: " + self.data['title_suffix']
end
end
class IconGenerator < Generator
##
# Iterate over every described icon in a YAML file and create a page for it
safe true
def generate(site)
site.icons.each do |icon|
site.pages << IconPage.new(site, site.source, site.config['icon_destination'], icon)
end
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/vendor/assets/components/font-awesome/src/_plugins/site.rb | vendor/assets/components/font-awesome/src/_plugins/site.rb | ##
# Provide an icons attribute on the site object
require 'yaml'
require 'forwardable'
module Jekyll
class Icon
attr_reader :name, :id, :unicode, :created, :categories
def initialize(icon_object)
@icon_object = icon_object
# Class name used in CSS and HTML
@icon_object['class'] = icon_object['id']
# Normalize the aliases
@icon_object['aliases'] ||= []
@name = icon_object['name']
@id = icon_object['id']
@class = icon_object['class']
@aliases = icon_object['aliases']
@unicode = icon_object['unicode']
@created = icon_object['created']
@categories = icon_object['categories']
end
def to_liquid
return @icon_object
end
end
class IconList
##
# A list of icons
#
include Enumerable
extend Forwardable
def_delegators :@icon_array, :each, :<<
def initialize(icon_array)
@original_icon_array = icon_array
@icon_array = []
icon_array.each { |icon_object|
@icon_array << Icon.new(icon_object)
}
end
def [](k)
@icon_array[k]
end
def to_liquid
@original_icon_array
end
end
module IconFilters
def expand_aliases(icons)
expanded = []
icons.each { |icon|
# Remove the aliases since we are expanding them
expanded << icon.reject{ |k| k == 'aliases'}
icon['aliases'].each { |alias_id|
alias_icon = expanded[-1].dup
alias_icon['class'] = alias_id
alias_icon['alias_of'] = icon
expanded << alias_icon
}
}
return expanded
end
def category(icons, cat)
icons.select { |icon| icon['categories'].include?(cat) }
end
def version(icons, version)
icons.select { |icon| icon['created'] == version }
end
def sort_by(icons, sort_key)
icons.sort_by! { |icon| icon[sort_key] }
end
end
Liquid::Template.register_filter(IconFilters)
class Site
attr_reader :icons
def process
self.reset_icons
self.reset
self.read
self.generate
self.render
self.cleanup
self.write
self.build
end
##
# Reads the YAML file that stores all data about icons
def reset_icons
@icons = IconList.new(YAML.load_file(self.config['icon_meta'])['icons'])
end
##
# After generation, runs a build of Font-Awesome
def build
system("make build", :chdir => self.config['destination'], :out => :err)
end
def site_payload
{
"site" => self.config.merge({
"time" => self.time,
"posts" => self.posts.sort { |a, b| b <=> a },
"pages" => self.pages,
"html_pages" => self.pages.reject { |page| !page.html? },
"categories" => post_attr_hash('categories'),
"tags" => post_attr_hash('tags')}),
"icons" => @icons,
}
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/simple_cov.rb | test/simple_cov.rb | require 'simplecov'
SimpleCov.start 'rails'
class SimpleCov::Formatter::QualityFormatter
def format(result)
SimpleCov::Formatter::HTMLFormatter.new.format(result)
File.open("coverage/covered_percent", "w") do |f|
f.puts result.source_files.covered_percent.to_f
end
end
end
SimpleCov.formatter = SimpleCov::Formatter::QualityFormatter | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/test_helper.rb | test/test_helper.rb | ENV["RAILS_ENV"] = "test"
require_relative "./simple_cov"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'factory_girl'
require 'mocha/setup'
FactoryGirl.find_definitions
class ActiveSupport::TestCase
def dump_database
User.delete_all
Provider.delete_all
Record.delete_all
db = Mongoid.default_session
db['measures'].drop()
db['selected_measures'].drop()
db['records'].drop
db['patient_cache'].drop
db['query_cache'].drop
end
def raw_post(action, body, parameters = nil, session = nil, flash = nil)
@request.env['RAW_POST_DATA'] = body
post(action, parameters, session, flash)
end
def basic_signin(user)
@request.env['HTTP_AUTHORIZATION'] = "Basic #{ActiveSupport::Base64.encode64("#{user.username}:#{user.password}")}"
end
def collection_fixtures(*collection_names)
collection_names.each do |collection|
MONGO_DB[collection].drop
Dir.glob(File.join(Rails.root, 'test', 'fixtures', collection, '*.json')).each do |json_fixture_file|
fixture_json = JSON.parse(File.read(json_fixture_file))
set_mongoid_ids(fixture_json)
MONGO_DB[collection].insert(fixture_json)
end
end
end
def set_mongoid_ids(json)
if json.kind_of?( Hash)
json.each_pair do |k,v|
if v && v.kind_of?( Hash )
if v["$oid"]
json[k] = BSON::ObjectId.from_string(v["$oid"])
else
set_mongoid_ids(v)
end
end
end
end
end
def hash_includes?(expected, actual)
if (actual.is_a? Hash)
(expected.keys & actual.keys).all? {|k| expected[k] == actual[k]}
elsif (actual.is_a? Array )
actual.any? {|value| hash_includes? expected, value}
else
false
end
end
def assert_false(value)
assert !value
end
def assert_query_results_equal(factory_result, result)
factory_result.each do |key, value|
assert_equal value, result[key] unless key == '_id'
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/unit/admin_rake_test.rb | test/unit/admin_rake_test.rb | require 'test_helper'
class AdminRakeTest < ActiveSupport::TestCase
@@rake = nil
setup do
dump_database
if (!@@rake)
@@rake = Rake.application
Rake.application = @@rake
Rake.application.rake_require "../../lib/tasks/admin"
Rake::Task.define_task(:environment)
end
Rake.application.tasks.each {|t| t.instance_eval{@already_invoked = false}}
end
teardown do
end
test "create an admin user" do
assert User.where(:username => 'pophealth').blank?
capture_stdout do
@@rake["admin:create_admin_account"].invoke
end
@admin = User.where(:username => 'pophealth').first
assert !@admin.blank?
assert @admin.approved?, "the created user should be approved"
assert @admin.admin?, "the created user should be an admin"
end
def capture_stdout(&block)
original_stdout = $stdout
$stdout = StringIO.new
begin
yield
ensure
$stdout = original_stdout
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/unit/user_rake_test.rb | test/unit/user_rake_test.rb | require 'test_helper'
class UserRakeTest < ActiveSupport::TestCase
@@rake = nil
setup do
dump_database
collection_fixtures 'users'
@unapproved_user = User.where({email: 'unapproved@test.com'}).first
@user = User.where({email: 'noadmin@test.com'}).first
@admin = User.where({email: 'admin@test.com'}).first
if (!@@rake)
@@rake = Rake.application
Rake.application = @@rake
Rake.application.rake_require "../../lib/tasks/popHealth_users"
Rake::Task.define_task(:environment)
end
Rake.application.tasks.each {|t| t.instance_eval{@already_invoked = false}}
end
teardown do
end
test "approve rake task approves user" do
assert !@unapproved_user.approved?
assert !@unapproved_user.admin?
ENV['USER_ID'] = @unapproved_user.username
capture_stdout do
@@rake["pophealth:users:approve"].invoke
end
@unapproved_user.reload
assert @unapproved_user.approved?
assert !@unapproved_user.admin?
end
test "admin rake task approves and grants admin using email" do
assert !@unapproved_user.approved?
assert !@unapproved_user.admin?
ENV['EMAIL'] = @unapproved_user.email
capture_stdout do
@@rake["pophealth:users:grant_admin"].invoke
end
@unapproved_user.reload
assert @unapproved_user.approved?
assert @unapproved_user.admin?
end
test "admin rake task makes a non-admin user an admin" do
assert !@user.admin?
ENV['USER_ID'] = @user.username
capture_stdout do
@@rake["pophealth:users:grant_admin"].invoke
end
@user.reload
assert @user.approved?
assert @user.admin?
end
test "revoke rake task makes a admin user a non-admin" do
assert @admin.admin?
ENV['USER_ID'] = @admin.username
capture_stdout do
@@rake["pophealth:users:revoke_admin"].invoke
end
@admin.reload
assert @admin.approved?
assert !@admin.admin?
end
def capture_stdout(&block)
original_stdout = $stdout
$stdout = StringIO.new
begin
yield
ensure
$stdout = original_stdout
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/unit/helpers/logs_helper_test.rb | test/unit/helpers/logs_helper_test.rb | require 'test_helper'
class LogsHelperTest < ActionView::TestCase
test "should be able to add the time to the rest of the params" do
existing_params = {:page => 4}
params[:log_start_date] = 'tomorrow'
time_range_params_plus(existing_params)
assert_equal 4, existing_params[:page]
assert_equal 'tomorrow', existing_params[:log_start_date]
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/unit/models/user_test.rb | test/unit/models/user_test.rb | require 'test_helper'
class UserTest < ActiveSupport::TestCase
setup do
dump_database
collection_fixtures 'users'
@user = User.where({email: 'noadmin@test.com'}).first
end
test "user should be found by username" do
found_user = User.by_username @user.username
assert_equal @user, found_user
end
test "user should be found by email" do
found_user = User.by_email @user.email
assert_equal @user, found_user
end
test "user preferences: selected_measure_ids replaces null with empty arrays" do
@user.preferences['selected_measure_ids'] = nil
assert @user.save
@user.reload
assert_equal [], @user.preferences['selected_measure_ids']
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/unit/models/provider_test.rb | test/unit/models/provider_test.rb | require 'test_helper'
class ProviderTest < ActiveSupport::TestCase
test "should import providers from OPML properly" do
provider_tree = ProviderTreeImporter.new(File.new('test/fixtures/providers.opml'))
provider_tree.load_providers(provider_tree.sub_providers)
leaf = Provider.where(:given_name => "Newington VANURS").first
first_parent = Provider.find(leaf.parent_id)
root = Provider.find(first_parent.parent_id)
assert_equal "6279AA", leaf.npi
assert_equal "6279AA", leaf.cda_identifiers.where(root: 'Facility').first.extension
assert_equal "627", first_parent.npi
assert_equal "627", first_parent.cda_identifiers.where(root: 'Division').first.extension
assert_equal "1", root.npi
assert_equal "1", root.cda_identifiers.where(root: 'VISN').first.extension
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/logs_controller_test.rb | test/functional/logs_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
class LogsControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@user = User.where({email: 'admin@test.com'}).first
sign_in @user
end
test "GET 'index'" do
get :index
assert_response :success
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/registrations_controller_test.rb | test/functional/registrations_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
class RegistrationsControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@user = User.where({email: 'noadmin@test.com'}).first
@user.password = "password"
@user.save
end
test "a signed in user can update their account information via HTML" do
@request.env['devise.mapping'] = Devise.mappings[:user]
sign_in @user
# passwords will be blank
put :update, user: { current_password: '', password: '', password_confirmation: '', company: 'The MITRE Corp' }
assert_response :redirect
assert_equal 'The MITRE Corp', assigns[:user].company
end
test "a signed in user can update their account information via JSON" do
@request.env['devise.mapping'] = Devise.mappings[:user]
sign_in @user
put :update, user: { company: 'The MITRE Corp' }, format: :json
assert_response :success
assert_equal 'The MITRE Corp', assigns[:user].company
end
test "a signed in user must supply their current password if they attempt to update their password via HTML" do
@request.env['devise.mapping'] = Devise.mappings[:user]
sign_in @user
put :update, user: {password: 'something new', password_confirmation: 'something new'}
assert_response :success
assert_equal ["Current password can't be blank"], assigns[:user].errors.full_messages
put :update, user: {current_password: 'password', password: 'something new', password_confirmation: 'something new'}
assert_response :redirect
end
test "a signed in user must supply their current password if they attempt to update their password via JSON" do
@request.env['devise.mapping'] = Devise.mappings[:user]
sign_in @user
put :update, user: {password: 'something new', password_confirmation: 'something new'}, format: :json
assert_response :not_acceptable
put :update, user: {current_password: 'password', password: 'something new', password_confirmation: 'something new'}, format: :json
assert_response :success
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/admin_controller_test.rb | test/functional/admin_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
class AdminControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@admin = User.where({email: 'admin@test.com'}).first
@user = User.where({email: 'noadmin@test.com'}).first
@user2 = User.where({email: 'noadmin2@test.com'}).first
@unapproved_user = User.where({email: 'unapproved@test.com'}).first
@admin2 = User.where({email: 'admin2@test.com'}).first
@user_ids = [] << @user.id
end
test "should get user list if admin" do
sign_in @admin
get :users
users = assigns[:users]
assert_not_nil users
assert_response :success
end
test "should not get user list if not admin" do
sign_in @user
get :users
users = assigns[:users]
assert_nil users
assert_response 403
end
test "promote user should make user admin" do
sign_in @admin
assert !@user.admin?
post :promote, username: @user.username, role: 'admin'
@user = User.find(@user.id)
assert @user.admin?
assert_response :success
end
test "demote user should make user not admin" do
sign_in @admin
assert @admin2.admin?
post :demote, username: @admin2.username, role: 'admin'
@admin2 = User.find(@admin2.id)
assert !@admin2.admin?
assert_response :success
end
test "should not be able to promote if not admin" do
sign_in @user
assert !@user.admin?
post :promote, username: @user.username, role: 'admin'
@user = User.find(@user.id)
assert !@user.admin?
assert_response 403
end
test "should not be able to demote if not admin" do
sign_in @user
assert @admin2.admin?
post :demote, username: @admin2.username, role: 'admin'
@admin2 = User.find(@admin2.id)
assert @admin2.admin?
assert_response 403
end
test "disable user should mark the user disabled" do
sign_in @admin
post :disable, username: @user2.username, disabled: 1
@user2.reload
assert @user2.disabled
assert_response :success
end
test "enable user should mark the user enabled" do
@user2.disabled = true
@user2.save!
assert @user2.disabled
sign_in @admin
post :disable, username: @user2.username, disabled: 0
@user2.reload
assert !@user2.disabled
assert_response :success
end
test "disable user should not disable the user if not admin" do
sign_in @user
post :disable, username: @user2.username, disabled: 1
@user2.reload
assert !@user2.disabled
assert_response 403
end
test "enable user should not enable the user if not admin" do
@user2.disabled = true
@user2.save!
assert @user2.disabled
sign_in @user
post :disable, username: @user2.username, disabled: 0
@user2.reload
assert @user2.disabled
assert_response 403
end
test "approve user should approve the user" do
sign_in @admin
assert !@unapproved_user.approved?
post :approve, username: @unapproved_user.username
@unapproved_user = User.find(@unapproved_user.id)
assert @unapproved_user.approved?
assert_response :success
end
test "approve user should not approve the user if not admin" do
sign_in @user
assert !@unapproved_user.approved?
post :approve, username: @unapproved_user.username
@unapproved_user = User.find(@unapproved_user.id)
assert !@unapproved_user.approved?
assert_response 403
end
test "disable invalid user should not freak out" do
sign_in @admin
post :disable, username: "crapusername"
assert_response :success
end
test "promote invalid user should not freak out" do
sign_in @admin
post :promote, username: "crapusername", role: 'admin'
assert_response :success
end
test "approve invalid user should not freak out" do
sign_in @admin
post :approve, username: "crapusername"
assert_response :success
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/providers_controller_test.rb | test/functional/api/providers_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
class ProvidersControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users', 'providers', 'measures'
@user = User.where({email: 'admin@test.com'}).first
@provider = Provider.where({family_name: "Darling"}).first
sign_in @user
end
test "get index" do
get :index
assert_not_nil assigns[:providers]
end
test "new" do
get :new, format: :json
assert_response :success
end
test "get show js" do
get :show, id: @provider.id, format: :json
assert_not_nil assigns[:provider]
assert_response :success
end
test "update provider" do
put :update, id: @provider.id, provider: @provider.attributes, format: :json
assert_response :success
end
test "get index via API" do
get :index, {format: :json}
json = JSON.parse(response.body)
assert_response :success
assert_equal(true, json.first.respond_to?(:keys))
end
test "create via API" do
provider = Provider.where({family_name: "Darling"}).first
provider_attributes = provider.attributes
provider_attributes.delete('_id')
post :create, :provider => provider_attributes
json = JSON.parse(response.body)
assert_response :success
assert_equal(true, json.respond_to?(:keys))
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/queries_controller_test.rb | test/functional/api/queries_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
class QueriesControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'measures'
collection_fixtures 'query_cache'
collection_fixtures 'records'
collection_fixtures 'patient_cache'
collection_fixtures 'providers'
collection_fixtures 'users'
@staff = User.where({email: 'noadmin@test.com'}).first
@admin = User.where({email: 'admin@test.com'}).first
@user = User.where({email: 'nostaff@test.com'}).first
@npi_user = User.where({email: 'npiuser@test.com'}).first
@npi_user.staff_role=false
@npi_user.save
@provider = Provider.where({family_name: "Darling"}).first
@provider.npi = @npi_user.npi
@provider.save
QME::QualityReport.where({}).each do |q|
if q.filters
q.filters["providers"] = [@provider.id]
q.save
end
end
QME::PatientCache.where({}).each do |pc|
if pc.value["filters"]
pc.value["filters"]["providers"] = [@provider.id]
pc.save
end
end
end
test "show admin" do
sign_in @admin
get :show, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "show npi" do
sign_in @npi_user
get :show, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "show unauthorized" do
sign_in @user
get :show, :id=>"523c57e2949d9dd06956b606"
assert_response 403
end
test "show staff_role" do
sign_in @staff
get :show, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "delete admin" do
sign_in @admin
delete :destroy, :id=>"523c57e2949d9dd06956b606"
assert_response 204
end
test "delete npi" do
sign_in @npi_user
delete :destroy, :id=>"523c57e2949d9dd06956b606"
assert_response 204
end
test "delete unauthorized" do
sign_in @user
delete :destroy, :id=>"523c57e2949d9dd06956b606"
assert_response 403
end
test "delete staff_role" do
sign_in @staff
delete :destroy, :id=>"523c57e2949d9dd06956b606"
assert_response 204
end
test "recalculate admin" do
sign_in @admin
get :recalculate, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "recalculate npi" do
sign_in @npi_user
get :recalculate, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "recalculate unauthorized" do
sign_in @user
get :recalculate, :id=>"523c57e2949d9dd06956b606"
assert_response 403
end
test "recalculate staff_role" do
sign_in @staff
get :recalculate, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "patient_results admin" do
sign_in @admin
get :patient_results, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "patient_results npi" do
sign_in @npi_user
get :patient_results, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "patient_results unauthorized" do
sign_in @user
get :patient_results, :id=>"523c57e2949d9dd06956b606"
assert_response 403
end
test "patient_results staff_role" do
sign_in @staff
get :patient_results, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "patients admin" do
sign_in @admin
get :patients, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "patients npi" do
sign_in @npi_user
get :patients, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "patients unauthorized" do
sign_in @user
get :patients, :id=>"523c57e2949d9dd06956b606"
assert_response 403
end
test "patients staff_role" do
sign_in @staff
get :patients, :id=>"523c57e2949d9dd06956b606"
assert_response :success
end
test "create admin" do
sign_in @admin
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212, :providers=>[@provider.id]
assert_response :success, "admin should be able to create reports for npis "
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212
assert_response :success, "admin should be able to create reports for no npi "
end
test "create staff" do
sign_in @staff
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212, :providers=>[@provider.id]
assert_response :success, "staff should be able to create all reports for npis"
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212
assert_response :success, "staff should be able to create all reports for no npi"
end
test "create npi user" do
sign_in @npi_user
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212, :providers=>[@provider.id]
assert_response :success, "should be able to create a quality report for users own npi"
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212
assert_response 403, "should be unauthorized without npi"
end
test "create unauthorized" do
sign_in @user
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212, :providers=>[@provider.id]
assert_response 403, "Should be unauthorized for npi"
post :create, :measure_id=>'40280381-3D61-56A7-013E-6649110743CE', :sub_id=>"a", :effective_date=>1212121212
assert_response 403, "Should be unauthorized with no npi"
end
test "filter patient results" do
sign_in @staff
get :patients, :id=>"523c57e4949d9dd06956b622"
assert_response :success
json = JSON.parse(response.body)
assert_equal 1, json.length
get :patients, :id=>"523c57e4949d9dd06956b622", :denex=>"true"
assert_response :success
json = JSON.parse(response.body)
assert_equal 0, json.length
get :patients, :id=>"523c57e4949d9dd06956b622", :denom=>"true"
assert_response :success
json = JSON.parse(response.body)
assert_equal 1, json.length
end
test "index admin" do
skip "need to implement"
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/patients_controller_test.rb | test/functional/api/patients_controller_test.rb | require 'test_helper'
module Api
class PatientsControllerTest < ActionController::TestCase
include Devise::TestHelpers
setup do
dump_database
collection_fixtures 'measures', 'patient_cache', 'records', 'users'
@user = User.where({email: 'admin@test.com'}).first
sign_in @user
end
test "view patient" do
get :show, id: '523c57e1b59a907ea9000064'
assert_response :success
end
test "view patient with include_results includes the results" do
@record = Record.find('523c57e1b59a907ea9000064')
get :show, id: @record.id, include_results: 'true', format: :json
assert_response :success
json = JSON.parse(response.body)
assert json.has_key?('measure_results')
assert_equal 2, json['measure_results'].length
end
test "uploading a patient record" do
cat1 = fixture_file_upload('test/fixtures/sample_cat1.xml', 'text/xml')
post :create, file: cat1
assert_response :success
end
test "results" do
@record = Record.find('523c57e1b59a907ea9000064')
get :results, id: @record.id
assert_response :success
json = JSON.parse(response.body)
assert_equal 2, json.length
get :results, id: @record.id, measure_id: "40280381-3D61-56A7-013E-6649110743CE", sub_id: "a"
assert_response :success
json = JSON.parse(response.body)
assert_equal 1, json.length
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/reports_controller_test.rb | test/functional/api/reports_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
class ReportsControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'measures'
collection_fixtures 'query_cache'
collection_fixtures 'records'
collection_fixtures 'patient_cache'
collection_fixtures 'providers'
collection_fixtures 'users'
@user = User.where({email: "noadmin@test.com"}).first
end
test "generate cat3" do
sign_in @user
get :cat3, :provider_id=> Provider.first.id
assert_response :success
cdastring = @response.body
assert cdastring.include? "ClinicalDocument"
cdastring.include? "2.16.840.1.113883.4.2"
end
test "generate cat1" do
sign_in @user
get :cat1, :id=>"523c57e1b59a907ea900000e", :measure_ids=>"40280381-3D61-56A7-013E-6649110743CE"
assert_response :success
cdastring = @response.body
assert cdastring.include? "ClinicalDocument"
assert cdastring.include? "Ella"
assert cdastring.include? "40280381-3D61-56A7-013E-6649110743CE"
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/measures_controller_test.rb | test/functional/api/measures_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
class MeasuresControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'measures', 'records', 'users'
@user = User.where({email: "noadmin@test.com"}).first
@admin = User.where({email: "admin@test.com"}).first
end
test "GET 'definition'" do
sign_in @user
get :show, :id => '0013'
assert_response :success
body = response.body
json = JSON.parse(body)
assert_equal "0013", json["hqmf_id"]
end
test "index" do
sign_in @user
get :index
assert_response :success
end
test "simple user cannot delete measures" do
sign_in @user
count = QME::QualityMeasure.where({"hqmf_id" => "0013"}).count
assert 0< count
delete :destroy, :id=>'0013'
assert_response 403
assert_equal count, QME::QualityMeasure.where({"hqmf_id" => "0013"}).count, "No measures should have been deleted"
end
test "admin can delete measures" do
sign_in @admin
count = QME::QualityMeasure.where({"hqmf_id" => "0013"}).count
assert 0< count, "should be at least one 0013 measure database"
delete :destroy, :id=>'0013'
assert_response 204
assert_equal 0, QME::QualityMeasure.where({"hqmf_id" => "0013"}).count, "There should be 0 measures with the HQMF id 0013 in the db"
end
test "create" do
skip "need to implement"
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/admin/providers_controller_test.rb | test/functional/api/admin/providers_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
module Admin
class ProvidersControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@admin = User.where({email: 'admin@test.com'}).first
@user = User.where({email: 'noadmin@test.com'}).first
end
test "count number of providers" do
sign_in @admin
get :count
assert_response :success
json = JSON.parse(response.body)
assert_equal json['provider_count'].is_a?(Integer), true
end
test "upload provider opml to admin api" do
sign_in @admin
providers = fixture_file_upload('test/fixtures/providers.opml', 'text/xml')
post :create, file: providers
assert_response :success
end
test "should delete providers if admin" do
sign_in @admin
delete :destroy
assert_response :success
end
test "should not delete providers if not admin" do
sign_in @user
delete :destroy
assert_response 403
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/admin/users_controller_test.rb | test/functional/api/admin/users_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
module Admin
class UsersControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@admin = User.where({email: 'admin@test.com'}).first
@user = User.where({email: 'noadmin@test.com'}).first
@unapproved_user = User.where({email: 'unapproved@test.com'}).first
@no_staff_user = User.where({email: 'unapproved@test.com'}).first
@admin2 = User.where({email: 'admin2@test.com'}).first
end
test "admin users index should return users in database" do
sign_in @admin
get :index
assert_response :success
json = JSON.parse(response.body)
assert_equal 9, json.count
end
test "promote user to admin" do
sign_in @admin
post :promote, id: @user.id, role: 'admin'
assert_response :success
@user.reload
assert_equal @user.admin, true
end
test "demote user from admin" do
sign_in @admin
post :demote, id: @admin2.id, role: 'admin'
assert_response :success
@admin2.reload
assert_equal @admin2.admin, false
end
test "promote user to staff role" do
sign_in @admin
post :promote, id: @no_staff_user.id, role: 'staff_role'
assert_response :success
@no_staff_user.reload
assert_equal @no_staff_user.staff_role, true
end
test "demote user from staff role" do
sign_in @admin
post :demote, id: @admin2.id, role: 'staff_role'
assert_response :success
@admin2.reload
assert_equal @admin2.staff_role, false
end
test "enable user account" do
sign_in @admin
get :enable, id: @unapproved_user.id
assert_response :success
@unapproved_user.reload
assert_equal @unapproved_user.disabled, false
end
test "disable user account" do
sign_in @admin
get :disable, id: @unapproved_user.id
assert_response :success
@unapproved_user.reload
assert_equal @unapproved_user.disabled, true
end
test "approve user account" do
sign_in @admin
get :approve, id: @unapproved_user.id
assert_response :success
@unapproved_user.reload
assert_equal @unapproved_user.approved, true
end
test "update user npi" do
sign_in @admin
get :update_npi, id: @user.id, npi: "NewNPI"
assert_response :success
@user.reload
assert_equal @user.npi, "NewNPI"
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/admin/patients_controller_test.rb | test/functional/api/admin/patients_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
module Admin
class PatientsControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@admin = User.where({email: 'admin@test.com'}).first
@user = User.where({email: 'noadmin@test.com'}).first
end
test "count number of patients" do
sign_in @admin
get :count
assert_response :success
json = JSON.parse(response.body)
assert_equal json['patient_count'].is_a?(Integer), true
end
test "should delete patients if admin" do
sign_in @admin
delete :destroy
assert_response :success
end
test "should not delete patients if not admin" do
sign_in @user
delete :destroy
assert_response 403
end
test "upload patients via zip" do
sign_in @admin
patients = fixture_file_upload('test/fixtures/patient_sample.zip', 'application/zip')
post :create, file: patients
assert_response :success
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/test/functional/api/admin/caches_controller_test.rb | test/functional/api/admin/caches_controller_test.rb | require 'test_helper'
include Devise::TestHelpers
module Api
module Admin
class CachesControllerTest < ActionController::TestCase
setup do
dump_database
collection_fixtures 'users'
@admin = User.where({email: 'admin@test.com'}).first
@user = User.where({email: 'noadmin@test.com'}).first
end
test "should fetch integer cache counts from DB" do
sign_in @admin
get :count
assert_response :success
json = JSON.parse(response.body)
assert_equal json['query_cache_count'].is_a?(Integer), true
assert_equal json['patient_cache_count'].is_a?(Integer), true
end
test "should delete caches if admin" do
sign_in @admin
delete :destroy
assert_response :success
end
test "should not delete caches if not admin" do
sign_in @user
delete :destroy
assert_response 403
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/spec/javascripts/support/jasmine_helper.rb | spec/javascripts/support/jasmine_helper.rb | #Use this file to set/override Jasmine configuration options
#You can remove it if you don't need it.
#This file is loaded *after* jasmine.yml is interpreted.
#
#Example: using a different boot file.
#Jasmine.configure do |config|
# @config.boot_dir = '/absolute/path/to/boot_dir'
# @config.boot_files = lambda { ['/absolute/path/to/boot_dir/file.js'] }
#end
#
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/oid_helper.rb | lib/oid_helper.rb | class OidHelper
def self.generate_oid_dictionary(measure)
valuesets = HealthDataStandards::SVS::ValueSet.in(oid: measure['oids'])
js = {}
valuesets.each do |vs|
js[vs['oid']] ||= {}
vs['concepts'].each do |con|
name = con['code_system_name']
js[vs['oid']][name] ||= []
js[vs['oid']][name] << con['code'].downcase unless js[vs['oid']][name].index(con['code'].downcase)
end
end
js.to_json
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/uniq_validator.rb | lib/uniq_validator.rb | # lib/email_validator.rb
class UniqValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
u = MONGO_DB['users'].find_one({attribute => value})
if u && (record.new_record? || record._id != u['_id'])
record.errors[attribute] << (options[:message] || "is not unique")
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/provider_tree_importer.rb | lib/provider_tree_importer.rb | require 'rexml/document'
class ProviderTreeImporter
class ProviderEntry
attr_accessor :attributes, :sub_providers
def initialize(element)
@attributes = map_attributes_to_hash(element.attributes)
@sub_providers = element.elements.map { |this| ProviderEntry.new(this) }
end
def flatten
@flatten ||= @sub_providers.map(&:flatten).unshift(self)
end
def to_s
@to_s ||= attributes['text'] || super
end
def respond_to?(method)
return true if attributes[method.to_s]
super
end
private
def map_attributes_to_hash(attributes)
list = {}
attributes.each { |key, value| list[key.underscore] = value }
end
end
attr_reader :sub_providers
def initialize(xml)
@doc = REXML::Document.new(xml)
@sub_providers = document_body ? initialize_subproviders_from_document_body : []
end
def flatten
@flatten ||= @sub_providers.map(&:flatten).flatten
end
def load_providers(provider_list, parent=nil)
provider_list.each do |sub|
prov = Provider.new(
:given_name => sub.attributes["name"],
:address => sub.attributes["address"],
)
possible_npi = sub.attributes["id"]
if possible_npi.present?
prov.npi = possible_npi
end
sub.attributes.each_pair do |root, extension|
unless ['tin', 'id', 'name', 'address', 'npi'].include? root
prov.cda_identifiers << CDAIdentifier.new(root: root, extension: extension)
end
end
if parent
parent.children << prov
end
prov.save
load_providers(sub.sub_providers, prov)
end
end
private
def document_body
@document_body ||= @doc.elements['opml/body']
end
def initialize_subproviders_from_document_body
document_body.elements.map { |element| ProviderEntry.new(element) }
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/import_archive_job.rb | lib/import_archive_job.rb | class ImportArchiveJob
attr_accessor :file, :current_user
def initialize(options)
@file = options['file'].path
@current_user = options['user']
end
def before
Log.create(:username => @current_user.username, :event => 'record import')
end
def perform
missing_patients = HealthDataStandards::Import::BulkRecordImporter.import_archive(File.new(@file))
missing_patients.each do |id|
Log.create(:username => @current_user.username, :event => "patient was present in patient manifest but not found after import", :medical_record_number => id)
end
end
def after
File.delete(@file)
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/qme/quality_report.rb | lib/qme/quality_report.rb | # Extending QualityReport so that updating a single patient can deal with
# OID dictionaries
module QME
class QualityReport
# Removes the cached results for the patient with the supplied id and
# recalculates as necessary
def self.update_patient_results(id)
# TODO: need to wait for any outstanding calculations to complete and then prevent
# any new ones from starting until we are done.
# drop any cached measure result calculations for the modified patient
QME::PatientCache.where('value.medical_record_id' => id).destroy()
# get a list of cached measure results for a single patient
sample_patient = QME::PatientCache.where({}).first
if sample_patient
cached_results = QME::PatientCache.where({'value.patient_id' => sample_patient['value']['patient_id']})
# for each cached result (a combination of measure_id, sub_id, effective_date and test_id)
cached_results.each do |measure|
# recalculate patient_cache value for modified patient
value = measure['value']
measure_model = QME::QualityMeasure.new(value['measure_id'], value['sub_id'])
oid_dictionary = OidHelper.generate_oid_dictionary(measure_model)
map = QME::MapReduce::Executor.new(value['measure_id'], value['sub_id'],
'effective_date' => value['effective_date'], 'test_id' => value['test_id'],
'oid_dictionary' => oid_dictionary)
map.map_record_into_measure_groups(id)
end
end
# remove the query totals so they will be recalculated using the new results for
# the modified patient
QME::QualityReport.where({}).each do |qr|
measure_model = QME::QualityMeasure.new(qr['measure_id'], qr['sub_id'])
oid_dictionary = OidHelper.generate_oid_dictionary(measure_model)
qr.calculate({"recalculate"=>true, "oid_dictionary" =>oid_dc},true)
end
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/measures/loader.rb | lib/measures/loader.rb | module Measures
class Loader
PARSERS = [HQMF::Parser::V2Parser,HQMF::Parser::V1Parser]
DRAFT_DIRECTORY = "tmp/draft_measures"
def self.parse_model(xml_path)
xml_contents = Nokogiri::XML(File.new xml_path)
parser = get_parser(xml_contents)
parser.parse(xml_contents)
end
def self.save_for_finalization(hqmf_model)
FileUtils.mkdir_p(DRAFT_DIRECTORY)
file = File.open(File.join(DRAFT_DIRECTORY,"#{hqmf_model.hqmf_id}.json"),"w") do |f|
f.puts hqmf_model.to_json.to_json
end
end
def self.finalize_measure(hqmf_id,nlm_user=nil,nlm_pass=nil,meta_data={})
json = JSON.parse(File.read(File.join(DRAFT_DIRECTORY,"#{hqmf_id}.json")))
hqmf_model = HQMF::Document.from_json(json)
generate_measures(hqmf_model,nlm_user,nlm_pass,meta_data)
end
def self.generate_measures(hqmf_model,nlm_user=nil,nlm_pass=nil, meta_data={})
#delete old measures
#delete old query cache entries
#delete old patient cache entries
existing = HealthDataStandards::CQM::Measure.where({hqmf_id: hqmf_model.hqmf_id}).to_a
qcache = HealthDataStandards::CQM::QueryCache.where({hqmf_id: hqmf_model.hqmf_id}).or({measure_id: hqmf_model.hqmf_id})
pcache = HealthDataStandards::CQM::PatientCache.where({"value.hqmf_id" => hqmf_model.hqmf_id}).or({"value.measure_id" => hqmf_model.hqmf_id})
load_valuesets(hqmf_model,nlm_user,nlm_pass,meta_data["force_update"])
measures = materialize_measures(hqmf_model,meta_data)
begin
measures.each do |m|
m.save!
end
rescue => e
measures.each do |m|
m.destroy if m.new_record?
end
raise e
end
existing.each do |m|
m.destroy
end
update_system_js
qcache.destroy
pcache.destroy
end
def self.load_valuesets(hqmf_document,vsac_user, vsac_pass, force_update=false)
vsac_config = APP_CONFIG["value_sets"]
vsac_user ||=vsac_config["nlm_user"]
vsac_pass ||=vsac_config["nlm_pass"]
api = HealthDataStandards::Util::VSApi.new(vsac_config["ticket_url"],vsac_config["api_url"],vsac_user,vsac_pass)
oids = hqmf_document.all_data_criteria.collect{|dc| dc.code_list_id}
oids.each do |oid|
exists = HealthDataStandards::SVS::ValueSet.where({oid: oid, bundle_id: nil}).count > 0
if (!exists || force_update)
begin
vs = api.get_valueset(oid)
doc = Nokogiri::XML(vs)
HealthDataStandards::SVS::ValueSet.load_from_xml(doc).save
rescue => e
raise "Error loading valuesets: #{e}"
end
end
end
end
def self.update_system_js
HealthDataStandards::Import::Bundle::Importer.save_system_js_fn('map_reduce_utils',
HQMF2JS::Generator::JS.map_reduce_utils)
HealthDataStandards::Import::Bundle::Importer.save_system_js_fn('hqmf_utils',
HQMF2JS::Generator::JS.library_functions(false))
end
def self.materialize_measures(hqmf_document, meta_data={})
continuous_variable = hqmf_document.populations.map {|x| x.keys}.flatten.uniq.include? HQMF::PopulationCriteria::MSRPOPL
value_sets = HealthDataStandards::SVS::ValueSet.in(oid: hqmf_document.all_code_set_oids)
measures = []
options = {
value_sets: value_sets,
episode_ids: meta_data["episode_ids"],
continuous_variable: continuous_variable
}
hqmf_document.populations.each_with_index do |pop,population_index|
measure = HealthDataStandards::CQM::Measure.new ({
nqf_id: hqmf_document.id || meta_data["nqf_id"],
hqmf_id: hqmf_document.hqmf_id,
hqmf_set_id: hqmf_document.hqmf_set_id,
hqmf_version_number: hqmf_document.hqmf_version_number,
cms_id: hqmf_document.cms_id,
name: hqmf_document.title,
title: hqmf_document.title,
description: hqmf_document.description,
type: meta_data["type"],
category: meta_data["category"],
map_fn: HQMF2JS::Generator::Execution.measure_js(hqmf_document, population_index, options),
continuous_variable: continuous_variable,
episode_of_care: meta_data["episode_of_care"],
hqmf_document: hqmf_document.to_json
})
measure.lower_is_better = meta_data["lower_is_better"]
measure["id"] = hqmf_document.hqmf_id
if (hqmf_document.populations.count > 1)
sub_ids = ('a'..'az').to_a
measure.sub_id = sub_ids[population_index]
measure.subtitle = measure.sub_id
measure.short_subtitle = measure.sub_id
end
if continuous_variable
observation = hqmf_document.population_criteria(hqmf_document.populations[population_index][HQMF::PopulationCriteria::OBSERV])
measure.aggregator = observation.aggregator
end
measure.oids = value_sets.map{|value_set| value_set.oid}.uniq
population_ids = {}
HQMF::PopulationCriteria::ALL_POPULATION_CODES.each do |type|
population_key = hqmf_document.populations[population_index][type]
population_criteria = hqmf_document.population_criteria(population_key)
if (population_criteria)
population_ids[type] = population_criteria.hqmf_id
end
end
stratification = hqmf_document.populations[population_index]['stratification']
if stratification
population_ids['stratification'] = stratification
end
measure.population_ids = population_ids
measures << measure
end
measures
end
def self.get_parser(doc)
PARSERS.each do |p|
if p.valid? doc
return p.new
end
end
raise "unknown document type"
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/hds/provider.rb | lib/hds/provider.rb | class Provider
field :level, type: String
embeds_many :cda_identifiers, class_name: "CDAIdentifier"
scope :alphabetical, ->{order_by([:family_name, :asc], [:given_name, :asc])}
scope :can_merge_with, ->(prov) { prov.npi.blank? ? all_except(prov) : all_except(prov).without_npi }
scope :all_except, ->(prov) { where(:_id.ne => prov.id) }
scope :selected, ->(provider_ids) { any_in(:_id => provider_ids)}
scope :selected_or_all, ->(provider_ids) { provider_ids.nil? || provider_ids.empty? ? Provider.all : Provider.selected(provider_ids) }
belongs_to :team
Specialties = {"100000000X" => "Behavioral Health and Social Service Providers",
"110000000X" => "Chiropractic Providers",
"120000000X" => "Dental Providers",
"130000000X" => "Dietary and Nutritional Service Providers",
"140000000X" => "Emergency Medical Service Providers",
"150000000X" => "Eye and Vision Service Providers",
"160000000X" => "Nursing Service Providers",
"180000000X" => "Pharmacy Service Providers (Individuals)",
"200000000X" => "Allopathic & Osteopathic Physicians",
"210000000X" => "Podiatric Medicine and Surgery Providers",
"220000000X" => "Respiratory, Rehabilitative and Restorative Service Providers",
"230000000X" => "Speech, Language and Hearing Providers",
"250000000X" => "Agencies",
"260000000X" => "Ambulatory Health Care Facilities",
"280000000X" => "Hospitals",
"290000000X" => "Laboratories",
"300000000X" => "Managed Care Organizations",
"310000000X" => "Nursing and Custodial Care Facilities",
"320000000X" => "Residential Treatment Facilities",
"330000000X" => "Suppliers (including Pharmacies and Durable Medical Equipment)",
"360000000X" => "Physician Assistants and Advanced Practice Nursing Providers"}
# alias :full_name :name
def full_name
[family_name, given_name].compact.join(", ")
end
def specialty_name
Specialties[specialty]
end
def merge_eligible
Provider.can_merge_with(self).alphabetical
end
def to_json(options={})
super(options)
end
def self.resolve_provider(provider_hash, patient=nil)
catch_all_provider_hash = { :title => "",
:given_name => "",
:family_name=> "",
:specialty => "",
:cda_identifiers => [{root: APP_CONFIG['orphan_provider']['root'], extension:APP_CONFIG['orphan_provider']['extension']}]
}
provider_info = provider_hash[:cda_identifiers].first
patient_id = patient.medical_record_number if patient
Log.create(:username => 'Background Event', :event => "No such provider with root '#{provider_info.root}' and extension '#{provider_info.extension}' exists in the database, patient has been assigned to the orphan provider.", :medical_record_number => patient_id)
provider ||= Provider.in("cda_identifiers.root" => APP_CONFIG['orphan_provider']['root']).and.in("cda_identifiers.extension" => APP_CONFIG['orphan_provider']['extension']).first
if provider.nil?
provider = Provider.create(catch_all_provider_hash)
Provider.root.children << provider
end
return provider
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/hds/record.rb | lib/hds/record.rb | class Record
include Mongoid::Document
# ===========================================================
# = This record extends the record in health data standards =
# ===========================================================
field :measures, type: Hash
scope :alphabetical, ->{order_by([:last, :asc], [:first, :asc])}
scope :with_provider, ->{where(:provider_performances.ne => nil).or(:provider_proformances.ne => [])}
scope :without_provider, ->{any_of({provider_performances: nil}, {provider_performances: []})}
scope :provider_performance_between, ->(effective_date) { where("provider_performances.start_date" => {"$lt" => effective_date}).and('$or' => [{'provider_performances.end_date' => nil}, 'provider_performances.end_date' => {'$gt' => effective_date}]) }
def language_names
lang_codes = (languages.nil?) ? [] : languages.map { |l| l.gsub(/\-[A-Z]*$/, "") }
Language.ordered.by_code(lang_codes).map(&:name)
end
def cache_results(params = {})
query = {"value.medical_record_id" => self.medical_record_number }
query["value.effective_date"]= params["effective_date"] if params["effective_date"]
query["value.measure_id"]= params["measure_id"] if params["measure_id"]
query["value.sub_id"]= params["sub_id"] if params["sub_id"]
HealthDataStandards::CQM::PatientCache.where(query)
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/hds/provider_performance.rb | lib/hds/provider_performance.rb | class ProviderPerformance
include Mongoid::Document
field :start_date, type: Integer
field :end_date, type: Integer
belongs_to :provider
embedded_in :record
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/hds/measure.rb | lib/hds/measure.rb | module HealthDataStandards
module CQM
class Measure
include Mongoid::Document
field :lower_is_better, type: Boolean
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/lib/hds/query_cache.rb | lib/hds/query_cache.rb | module HealthDataStandards
module CQM
class QueryCache
# FIXME:
def self.aggregate_measure(measure_id, effective_date, filters=nil, test_id=nil)
query_hash = {'effective_date' => effective_date, 'measure_id' => measure_id,
'test_id' => test_id}
if filters
query_hash.merge!(filters)
end
cache_entries = self.where(query_hash)
aggregate_count = AggregateCount.new(measure_id)
cache_entries.each do |cache_entry|
aggregate_count.add_entry(cache_entry)
end
aggregate_count
end
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/application.rb | config/application.rb | require File.expand_path('../boot', __FILE__)
#require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
#require "active_resource/railtie"
require "rails/test_unit/railtie"
require "sprockets/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module PopHealth
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(#{Rails.root}/lib/hds)
config.autoload_paths += %W(#{Rails.root}/lib/measures)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
config.relative_url_root = ""
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
# add devise views
# config.paths["app/views/devise"]
config.paths["app/views"] << "app/views/devise"
require 'will_paginate/array'
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/environment.rb | config/environment.rb | # Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
PopHealth::Application.initialize!
require_relative '../lib/oid_helper'
require_relative '../lib/hds/record.rb'
require_relative '../lib/hds/provider.rb'
require_relative '../lib/hds/query_cache.rb'
require_relative '../lib/hds/provider_performance.rb'
require_relative '../lib/qme/quality_report.rb'
require_relative '../lib/import_archive_job.rb'
require_relative '../lib/provider_tree_importer.rb'
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/routes.rb | config/routes.rb | PopHealth::Application.routes.draw do
apipie
devise_for :users, :controllers => {:registrations => "registrations"}
get "admin/users"
post "admin/promote"
post "admin/demote"
post "admin/approve"
post "admin/disable"
post "admin/update_npi"
get "admin/patients"
put "admin/upload_patients"
put "admin/upload_providers"
delete "admin/remove_patients"
delete "admin/remove_caches"
delete "admin/remove_providers"
post 'api/measures/finalize'
post 'api/measures/update_metadata'
get "logs/index"
root :to => 'home#index'
resources :providers do
resources :patients do
collection do
get :manage
put :update_all
end
end
member do
get :merge_list
put :merge
end
end
resources :teams
namespace :api do
get 'reports/qrda_cat3.xml', :to =>'reports#cat3', :format => :xml
get 'reports/cat1/:id/:measure_ids', :to =>'reports#cat1', :format => :xml
namespace :admin do
resource :caches do
collection do
get :count
end
end
resource :patients do
collection do
get :count
end
end
resource :providers do
collection do
get :count
end
end
resources :users do
member do
get :enable
get :disable
post :promote
post :demote
get :approve
get :update_npi
end
end
end
resources :providers do
resources :patients do
collection do
get :manage
put :update_all
end
end
end
resources :patients do
member do
get :results
end
end
resources :measures
resources :queries do
member do
get :patients
get :patient_results
put :recalculate
end
end
end
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/boot.rb | config/boot.rb | require 'rubygems'
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/active_model_serializers.rb | config/initializers/active_model_serializers.rb | ActiveSupport.on_load(:active_model_serializers) do
# Disable for all serializers (except ArraySerializer)
ActiveModel::Serializer.root = false
# Disable for ArraySerializer
ActiveModel::ArraySerializer.root = false
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/apipie.rb | config/initializers/apipie.rb | Apipie.configure do |config|
config.app_name = "popHealth"
config.api_base_url = "/api"
config.doc_base_url = "/apipie"
config.default_version = "3.0"
config.api_controllers_matcher = ["#{Rails.root}/app/controllers/api/*.rb", "#{Rails.root}/app/controllers/api/admin/*.rb"]
config.app_info = <<-EOS
API documentation for popHealth. This API is used by the web front end of popHealth but
it can also be used to interact with patient information and clinical quality measure
calculations from external applications.
EOS
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/session_store.rb | config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
PopHealth::Application.config.session_store :cookie_store, :key => '_popHealth_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# PopHealth::Application.config.session_store :active_record_store
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/devise.rb | config/initializers/devise.rb | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/mongoid'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication.
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "cbc8134884052b5948d20a36d3b006b30e4cd0a68e4304a0f5ca4cd5a2713fc63d604d30b17a2e02704b7c1b9c17e5c40d97d8ef8542fa498df021498bcd57a6"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 6..128.
# config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
config.http_authenticatable = true
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: "/my_engine"
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = "/my_engine/users/auth"
config.secret_key = 'e8e19f73d96b32d12776ed08a35b274eeea4fbcd4bfb381734e54b8deb2f849b352856342a74bed259cbad92d481b343d7eb29294f2764293b9343d6b7e64a32'
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/handlebars_assets.rb | config/initializers/handlebars_assets.rb | HandlebarsAssets::Config.template_namespace = 'JST' | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/non_digest_assets.rb | config/initializers/non_digest_assets.rb | NonStupidDigestAssets.whitelist = [/glyphicons-halflings-regular.*/, /fontawesome-webfont.*/]
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/wrap_parameters.rb | config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/inflections.rb | config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/mongo.rb | config/initializers/mongo.rb | MONGO_DB = Mongoid.default_session
# js_collection = MONGO_DB['system.js']
# unless js_collection.find_one('_id' => 'contains')
# js_collection.save('_id' => 'contains',
# 'value' => BSON::Code.new("function( obj, target ) { return obj.indexOf(target) != -1; };"))
# end
# # create a unique index for patient cache, this prevents a race condition where the same patient can be entered multiple times for a patient
# MONGO_DB.collection('patient_cache').ensure_index([['value.measure_id', Mongo::ASCENDING], ['value.sub_id', Mongo::ASCENDING], ['value.effective_date', Mongo::ASCENDING], ['value.patient_id', Mongo::ASCENDING]], {'unique'=> true})
# base_fields = [['value.measure_id', Mongo::ASCENDING], ['value.sub_id', Mongo::ASCENDING], ['value.effective_date', Mongo::ASCENDING], ['value.test_id', Mongo::ASCENDING], ['value.manual_exclusion', Mongo::ASCENDING]]
# %w(population denominator numerator antinumerator exclusions).each do |group|
# MONGO_DB.collection('patient_cache').ensure_index(base_fields.clone.concat([["value.#{group}", Mongo::ASCENDING]]), {name: "#{group}_index"})
# end
module QME
module DatabaseAccess
# Monkey patch in the connection for the application
def get_db
MONGO_DB
end
end
end
# TODO Set indexes | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/popHealth.rb | config/initializers/popHealth.rb | require 'hqmf-parser'
APP_CONFIG = YAML.load_file(Rails.root.join('config', 'popHealth.yml'))[Rails.env]
# insert languages
(
JSON.parse(File.read(File.join(Rails.root, 'test', 'fixtures', 'code_sets', 'languages.json'))).each do |document|
MONGO_DB['languages'].insert(document)
end
) if MONGO_DB['languages'].find({}).count == 0
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/version_from_git.rb | config/initializers/version_from_git.rb | begin
#This pulls the commit hash first-6 and most recent tag from git
g = Git.open(".")
PopHealth::Application.config.commit = g.log.first.objectish.slice(0,6)
last_tag = g.tags.last
PopHealth::Application.config.tag = last_tag ? last_tag.name : "Unknown"
rescue ArgumentError => e
#Path does not exist
PopHealth::Application.config.commit = "Unknown"
PopHealth::Application.config.tag = "Unknown"
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/backtrace_silencers.rb | config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/mime_types.rb | config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/secret_token.rb | config/initializers/secret_token.rb | # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
PopHealth::Application.config.secret_token = 'd2d8152dfb0736f5ae682c88a0e416c0104b9c0271ac9834d7349653c96f38715b94fc9bad48641725b149a83e59e77d0e7554cd407bb1771f9d343ce217c596'
PopHealth::Application.config.secret_key_base = '3e393dd55e17e1836ea8c7feb65595d120bc2f23a58e811f1e2256dc6de615704b99c964f4149c33b4728f566a16bde4bae2a1eecc49fe7715057de4932f0f8f' | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/warden_logging.rb | config/initializers/warden_logging.rb | Warden::Manager.after_authentication do |user,auth,opts|
Log.create(:username => user.username, :event => 'login')
end
Warden::Manager.before_failure do |env, opts|
request = Rack::Request.new(env)
attempted_login_name = request.params[:user].try(:[], :username)
attempted_login_name ||= 'unknown'
Log.create(:username => attempted_login_name, :event => 'failed login attempt')
end
Warden::Manager.before_logout do |user,auth,opts|
#this has a chance of getting called with a nil user, in which case we skip logging
#TODO: figure out why this has a chance of getting called with a nil user (only happens from 403 page)
if user
Log.create(:username => user.username, :event => 'logout')
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/initializers/bson/object_id.rb | config/initializers/bson/object_id.rb | module BSON
class ObjectId
def as_json(options = {})
to_s
end
end
end | ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/environments/test.rb | config/environments/test.rb | PopHealth::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {:host => 'localhost', :port => 3000}
config.eager_load = false
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
# Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
config.assets.allow_debugging = true
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/environments/development.rb | config/environments/development.rb | PopHealth::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
# config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = {:host => 'localhost', :port => 3000}
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.eager_load = false
# Add spec/javascripts to asset paths so that jasmine tests work
config.assets.paths << Rails.root.join('spec/javascripts')
#add support for Pry debugging
silence_warnings do
begin
require 'pry'
IRB = Pry
rescue LoadError
end
end
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
pophealth/popHealth | https://github.com/pophealth/popHealth/blob/cdcbe7b7d7374cce48d03e456ac5daca1d315d43/config/environments/production.rb | config/environments/production.rb | PopHealth::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = false
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
config.assets.precompile << '*.scss'
config.assets.precompile << 'jquery.js'
config.assets.precompile << 'jquery_ujs.js'
config.assets.precompile << 'bootstrap/fonts/glyphicons-halflings-regular.*'
config.assets.precompile << 'font-awesome/fonts/fontawesome-webfont.*'
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
config.eager_load = true
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
| ruby | Apache-2.0 | cdcbe7b7d7374cce48d03e456ac5daca1d315d43 | 2026-01-04T17:51:51.385519Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/jobs/user_export_file_job.rb | app/jobs/user_export_file_job.rb | class UserExportFileJob < ApplicationJob
queue_as :enju_leaf
def perform(user_export_file)
user_export_file.export!
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/jobs/resource_import_file_job.rb | app/jobs/resource_import_file_job.rb | class ResourceImportFileJob < ApplicationJob
queue_as :enju_leaf
def perform(resource_import_file)
resource_import_file.import_start
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.