help me refactor this code and make it as simple as possible: def…
- User
help me refactor this code and make it as simple as possible: def limit_rows_and_cols_based_on_emp_role(query) return query if employee.admin?
config_file = load_yml_file('config/settings/reporting/accessable_columns_based_on_emp_role.yml') product_key = report.products.last.key role = employee.role_type.downcase.split(' ').join('_') allowed_product_dims = config_file['allowed_columns'][role][product_key]['dimensions'] allowed_product_measures = config_file['allowed_columns'][role][product_key]['measures'] allowed_global_dims = config_file['allowed_columns'][role]['global']['dimensions'] allowed_global_measures = config_file['allowed_columns'][role]['global']['measures'] allowed_product_dim_members = config_file['options'][product_key]['dimensions'].map { |k, v| v['member'] if allowed_product_dims.include?(k) }.compact allowed_product_measure_members = config_file['options'][product_key]['measures'].map { |k, v| v['member'] if allowed_product_measures.include?(k) }.compact allowed_global_dim_members = config_file['options']['global']['dimensions'].map { |k, v| v['member'] if allowed_global_dims.include?(k) }.compact allowed_global_measure_members = config_file['options']['global']['measures'].map { |k, v| v['member'] if allowed_global_measures.include?(k) }.compact all_allowed_dim_members = allowed_product_dim_members + allowed_global_dim_members all_allowed_measure_members = allowed_product_measure_members + allowed_global_measure_members query['dimensions'].delete_if { |dim| !all_allowed_dim_members.include?(dim) } query['measures'].delete_if { |measure| !all_allowed_measure_members.include?(measure) } query end - Assistant
Certainly! Let's refactor your code to make it as simple and concise as possible by eliminating repetition and extracting helper methods. Here's the refactored version:
def limit_rows_and_cols_based_on_emp_role(query) return query if employee.admin? config = load_yml_file('config/settings/reporting/accessable_columns_based_on_emp_role.yml') role = employee.role_type.downcase.tr(' ', '_') product_key = report.products.last.key allowed_dimensions = allowed_members(config, role, [product_key, 'global'], 'dimensions') allowed_measures = allowed_members(config, role, [product_key, 'global'], 'measures') query['dimensions'].select! { |dim| allowed_dimensions.include?(dim) } query['measures'].select! { |measure| allowed_measures.include?(measure) } query end private def allowed_members(config, role, scopes, type) scopes.flat_map do |scope| keys = config.dig('allowed_columns', role, scope, type) || [] options = config.dig('options', scope, type) || {} keys.map { |key| options.dig(key, 'member') } end.compact.uniq end