ruby on rails - How can I make this method more concise? -


i warning when running reek on rails project:

[36]:arborreloaded::userstoryservice#destroy_stories has approx 8 statements (toomanystatements)

here's method:

def destroy_stories(project_id, user_stories)   errors = []   @project = project.find(project_id)   user_stories.each |current_user_story_id|     unless @project.user_stories.find(current_user_story_id).destroy       errors.push("error destroying user_story: #{current_user_story_id}")     end   end   if errors.compact.length == 0     @common_response.success = true   else     @common_response.success = false     @common_response.errors = errors   end   @common_response end 

how can method minimized?

first, find class , method size useful finding code might need refactoring, need long class or method. , there way make code shorter around such limits, might make less readable. disable type of inspection when using static analysis tools.

also, it's unclear me why you'd expect have error when deleting story, or benefits error message includes id , nothing error occurred.

that said, i'd write method this, reduce explicit local state , better separate concerns:

def destroy_stories(project_id, story_ids)   project = project.find(project_id) # don't see need instance variable   errors = story_ids.     select { |story_id| !project.user_stories.find(story_id).destroy }.     map { |story_id| "error destroying user_story: #{story_id}" }   respond errors end  # lots of services need this, can go in superclass. # better, move @common_response's class. def respond(errors)   # best move behavior @common_response.   @common_response.success = errors.any?   # works when errors == []. if not, fix framework.   @common_response.errors = errors   @common_response end 

you can see how taking care in framework can save lot of noise in components.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -