<commit_before>class ChillDocument < NSPersistentDocument
  attr_accessor :request_url, :request_method, :output, :indicator, :headers_tab_view

  attr_accessor :engine

  def init
    if super
      @engine = Wrapper.new
      @engine.delegate = self
      self
    end
  end

  # Name of nib containing document window
  def windowNibName
    'ChillDocument'
  end

  # Document data representation for saving (return NSData)
  def dataOfType(type, error:outError)
    outError.assign(NSError.errorWithDomain(NSOSStatusErrorDomain, code:-4, userInfo:nil))
    nil
  end

  # Read document from data (return non-nil on success)
  def readFromData(data, ofType:type, error:outError)
    outError.assign(NSError.errorWithDomain(NSOSStatusErrorDomain, code:-4, userInfo:nil))
    nil
  end

  # Return lowercase 'untitled', to comply with HIG
  def displayName
    fileURL ? super : super.sub(/^[[:upper:]]/) {|s| s.downcase}
  end




  # GUI Actions
  def rest_call(sender)
    url = NSURL.URLWithString(request_url.stringValue)
    verb = request_method.titleOfSelectedItem

    start_indicator
    output.string = ''
    clear_response_parameters

    @engine.sendRequestTo(url, usingVerb:verb, withParameters:request_parameters)
  end




  # REST Wrapper Delegates
  def wrapper(engine, didRetrieveData:data)
    response = engine.httpResponse
    headers = response.allHeaderFields

    headers.each_pair do |key, value|
      parameter = NSEntityDescription.insertNewObjectForEntityForName("Parameter", inManagedObjectContext:self.managedObjectContext)
      parameter.setValue(key, forKey:'name')
      parameter.setValue(value, forKey:'value')
      parameter.setValue('response', forKey:'kind')
    end

    text = engine.responseAsText
    if text
      output.string = text
      stop_indicator
      show_response_tab
    end
  end

  def wrapperHasBadCredentials(wrapper)
    # handle this in here by showing an overlay in which you can enter your credentials
    stop_indicator
    alert = NSAlert.alertWithMessageText("Bad credentials!", defaultButton:"OK", alternateButton:nil, otherButton:nil, informativeTextWithFormat:"Please specify a valid username and password")
    alert.runModal
  end

  def wrapper(wrapper, didCreateResourceAtURL:url)
    stop_indicator
    alert = NSAlert.alertWithMessageText("Resource created at #{url}", defaultButton:"OK", alternateButton:nil, otherButton:nil, informativeTextWithFormat:"")
    alert.runModal
  end

  def wrapper(wrapper, didFailWithError:error)
    stop_indicator
    alert = NSAlert.alertWithError(error)
    alert.runModal
  end

  #def wrapper(wrapper, didReceiveStatusCode:statusCode)
  # stop_indicator
  # alert = NSAlert.alertWithMessageText("Status code not OK", defaultButton:"OK", alternateButton:nil, otherButton:nil, informativeTextWithFormat:"I am an alert!")
  # alert.runModal
  #end

  private

  def start_indicator
    indicator.setHidden(false)
    indicator.startAnimation(self)
  end

  def stop_indicator
    indicator.setHidden(true)
    indicator.stopAnimation(self)
  end

  def show_response_tab
    headers_tab_view.selectLastTabViewItem(self)
  end

  def clear_response_parameters
    context = self.managedObjectContext

    response_parameters_request = NSFetchRequest.alloc.init
    response_parameters_request.entity = NSEntityDescription.entityForName('Parameter', inManagedObjectContext:context)
    response_parameters_request.predicate = NSPredicate.predicateWithFormat("%K LIKE %@", 'kind', 'response', 'name', 'value')

    error = nil
    array = context.executeFetchRequest(response_parameters_request, error:error)

    if array.size > 0
      array.each do |parameter|
        context.deleteObject(parameter)
      end
    else
      parameters = nil
    end
  end

  def request_parameters
    parameters = {}
    begin
      context = self.managedObjectContext

      request_parameters_request = NSFetchRequest.alloc.init
      request_parameters_request.entity = NSEntityDescription.entityForName('Parameter', inManagedObjectContext:context)
      request_parameters_request.predicate = NSPredicate.predicateWithFormat("%K LIKE %@ AND %K != NIL AND %K != NIL", 'kind', 'request', 'name', 'value')

      error = nil
      array = context.executeFetchRequest(request_parameters_request, error:error)

      if array.size > 0
        array.each do |parameter|
          parameters[parameter.valueForKey('name')] = parameter.valueForKey('value')
        end
      else
        parameters = nil
      end
    rescue => e
      puts "Error while building parameters: #{e}"
    end
    parameters
  end
end
<commit_msg>More MacRuby like initializers for the NSFetchRequests's<commit_after>class ChillDocument < NSPersistentDocument
  attr_accessor :request_url, :request_method, :output, :indicator, :headers_tab_view

  attr_accessor :engine

  def init
    if super
      @engine = Wrapper.new
      @engine.delegate = self
      self
    end
  end

  # Name of nib containing document window
  def windowNibName
    'ChillDocument'
  end

  # Document data representation for saving (return NSData)
  def dataOfType(type, error:outError)
    outError.assign(NSError.errorWithDomain(NSOSStatusErrorDomain, code:-4, userInfo:nil))
    nil
  end

  # Read document from data (return non-nil on success)
  def readFromData(data, ofType:type, error:outError)
    outError.assign(NSError.errorWithDomain(NSOSStatusErrorDomain, code:-4, userInfo:nil))
    nil
  end

  # Return lowercase 'untitled', to comply with HIG
  def displayName
    fileURL ? super : super.sub(/^[[:upper:]]/) {|s| s.downcase}
  end




  # GUI Actions
  def rest_call(sender)
    url = NSURL.URLWithString(request_url.stringValue)
    verb = request_method.titleOfSelectedItem

    start_indicator
    output.string = ''
    clear_response_parameters

    @engine.sendRequestTo(url, usingVerb:verb, withParameters:request_parameters)
  end




  # REST Wrapper Delegates
  def wrapper(engine, didRetrieveData:data)
    response = engine.httpResponse
    headers = response.allHeaderFields

    headers.each_pair do |key, value|
      parameter = NSEntityDescription.insertNewObjectForEntityForName("Parameter", inManagedObjectContext:self.managedObjectContext)
      parameter.setValue(key, forKey:'name')
      parameter.setValue(value, forKey:'value')
      parameter.setValue('response', forKey:'kind')
    end

    text = engine.responseAsText
    if text
      output.string = text
      stop_indicator
      show_response_tab
    end
  end

  def wrapperHasBadCredentials(wrapper)
    # handle this in here by showing an overlay in which you can enter your credentials
    stop_indicator
    alert = NSAlert.alertWithMessageText("Bad credentials!", defaultButton:"OK", alternateButton:nil, otherButton:nil, informativeTextWithFormat:"Please specify a valid username and password")
    alert.runModal
  end

  def wrapper(wrapper, didCreateResourceAtURL:url)
    stop_indicator
    alert = NSAlert.alertWithMessageText("Resource created at #{url}", defaultButton:"OK", alternateButton:nil, otherButton:nil, informativeTextWithFormat:"")
    alert.runModal
  end

  def wrapper(wrapper, didFailWithError:error)
    stop_indicator
    alert = NSAlert.alertWithError(error)
    alert.runModal
  end

  #def wrapper(wrapper, didReceiveStatusCode:statusCode)
  # stop_indicator
  # alert = NSAlert.alertWithMessageText("Status code not OK", defaultButton:"OK", alternateButton:nil, otherButton:nil, informativeTextWithFormat:"I am an alert!")
  # alert.runModal
  #end

  private

  def start_indicator
    indicator.setHidden(false)
    indicator.startAnimation(self)
  end

  def stop_indicator
    indicator.setHidden(true)
    indicator.stopAnimation(self)
  end

  def show_response_tab
    headers_tab_view.selectLastTabViewItem(self)
  end

  def clear_response_parameters
    context = self.managedObjectContext

    response_parameters_request = NSFetchRequest.new
    response_parameters_request.entity = NSEntityDescription.entityForName('Parameter', inManagedObjectContext:context)
    response_parameters_request.predicate = NSPredicate.predicateWithFormat("%K LIKE %@", 'kind', 'response', 'name', 'value')

    error = nil
    array = context.executeFetchRequest(response_parameters_request, error:error)

    if array.size > 0
      array.each do |parameter|
        context.deleteObject(parameter)
      end
    else
      parameters = nil
    end
  end

  def request_parameters
    parameters = {}
    begin
      context = self.managedObjectContext

      request_parameters_request = NSFetchRequest.new
      request_parameters_request.entity = NSEntityDescription.entityForName('Parameter', inManagedObjectContext:context)
      request_parameters_request.predicate = NSPredicate.predicateWithFormat("%K LIKE %@ AND %K != NIL AND %K != NIL", 'kind', 'request', 'name', 'value')

      error = nil
      array = context.executeFetchRequest(request_parameters_request, error:error)

      if array.size > 0
        array.each do |parameter|
          parameters[parameter.valueForKey('name')] = parameter.valueForKey('value')
        end
      else
        parameters = nil
      end
    rescue => e
      puts "Error while building parameters: #{e}"
    end
    parameters
  end
end

{'fraction_non_alphanumeric': 0.08368336025848142, 'fraction_numerical': 0.0008616047388260636, 'mean_word_length': 4.016747703943814, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5168362', 'n_tokens_mistral': 2721, 'n_tokens_neox': 2642, 'n_words': 616}